#!/usr/bin/env node
/**
 * 构建 harmony/rnaa.har(在 .rn-build/har_wrapper 一次性工程中编译)
 */
import { execFileSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const MODULE_NAME = 'rnaa';
const OHOS_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const HARMONY_DIR = path.join(OHOS_DIR, 'harmony');
const MODULE_SRC = path.join(HARMONY_DIR, MODULE_NAME);
const WRAPPER = path.join(OHOS_DIR, '.rn-build', 'har_wrapper');

const GENERATED = new Set(['build', '.hvigor', '.cxx', 'oh_modules', 'BuildProfile.ets', 'oh-package-lock.json5']);

const buildMode = process.argv.includes('--release') ? 'release' : 'debug';
const isWindows = process.platform === 'win32';
const studioHome = process.env.DEVECO_STUDIO_HOME;
if (!studioHome) {
  throw new Error('请设置 DEVECO_STUDIO_HOME 为 DevEco Studio 安装目录');
}
const studioNode = path.join(studioHome, 'tools', 'node', isWindows ? 'node.exe' : 'bin/node');
const studioHvigor = path.join(studioHome, 'tools', 'hvigor', 'bin', 'hvigorw.js');
const studioOhpm = path.join(studioHome, 'tools', 'ohpm', 'bin', isWindows ? 'ohpm.bat' : 'ohpm');
process.env.DEVECO_SDK_HOME ??= path.join(studioHome, 'sdk');

function run(cmd, args, cwd) {
  console.log(`\n$ ${cmd} ${args.join(' ')}`);
  if (cmd === 'hvigorw') {
    execFileSync(studioNode, [studioHvigor, ...args], { cwd, stdio: 'inherit' });
  } else if (isWindows) {
    execFileSync(studioNode, [path.join(path.dirname(studioOhpm), 'pm-cli.js'), ...args], { cwd, stdio: 'inherit' });
  } else {
    execFileSync(studioOhpm, args, { cwd, stdio: 'inherit' });
  }
}

function writeJson5(relPath, contents) {
  const full = path.join(WRAPPER, relPath);
  fs.mkdirSync(path.dirname(full), { recursive: true });
  fs.writeFileSync(full, contents);
}

const moduleManifest = JSON.parse(fs.readFileSync(path.join(MODULE_SRC, 'oh-package.json5'), 'utf8'));
console.log(`使用 OHPM RNOH: ${moduleManifest.dependencies['@rnoh/react-native-openharmony']}`);

console.log(`清理 ${path.relative(OHOS_DIR, WRAPPER)}`);
if (!WRAPPER.startsWith(OHOS_DIR + path.sep) || path.basename(WRAPPER) !== 'har_wrapper') {
  throw new Error('HAR 构建目录超出当前仓库');
}
fs.rmSync(WRAPPER, { recursive: true, force: true });
fs.mkdirSync(WRAPPER, { recursive: true });

fs.cpSync(MODULE_SRC, path.join(WRAPPER, MODULE_NAME), {
  recursive: true,
  filter: (src) => !GENERATED.has(path.basename(src)),
});

writeJson5('AppScope/app.json5', `{
  "app": {
    "bundleName": "com.hxa.rn.appauth.harbuild",
    "vendor": "example",
    "versionCode": 1000000,
    "versionName": "1.0.0"
  }
}
`);

writeJson5('build-profile.json5', `{
  "app": {
    "products": [
      {
        "name": "default",
        "compatibleSdkVersion": "5.0.5(17)",
        "runtimeOS": "HarmonyOS",
        "buildOption": {
          "strictMode": {
            "caseSensitiveCheck": true,
            "useNormalizedOHMUrl": true
          }
        }
      }
    ],
    "buildModeSet": [
      { "name": "debug" },
      { "name": "release" }
    ]
  },
  "modules": [
    {
      "name": "${MODULE_NAME}",
      "srcPath": "./${MODULE_NAME}",
      "targets": [
        {
          "name": "default",
          "applyToProducts": ["default"]
        }
      ]
    }
  ]
}
`);

writeJson5('hvigorfile.ts', `import { appTasks } from '@ohos/hvigor-ohos-plugin';

export default {
  system: appTasks,
  plugins: []
}
`);

writeJson5('hvigor/hvigor-config.json5', `{
  "modelVersion": "5.0.5",
  "dependencies": {},
  "execution": {},
  "logging": {},
  "debugging": {},
  "nodeOptions": {}
}
`);

writeJson5('oh-package.json5', `{
  "modelVersion": "5.0.5",
  "description": "一次性工程,仅用于构建 ${MODULE_NAME}.har。",
  "dependencies": {},
  "devDependencies": {}
}
`);

run('ohpm', ['install'], WRAPPER);
run('hvigorw', [
  'assembleHar',
  '--mode', 'module',
  '-p', `module=${MODULE_NAME}@default`,
  '-p', 'product=default',
  '-p', `buildMode=${buildMode}`,
  '--no-daemon',
], WRAPPER);

const built = path.join(WRAPPER, MODULE_NAME, 'build', 'default', 'outputs', 'default', `${MODULE_NAME}.har`);
if (!fs.existsSync(built)) {
  console.error(`构建未产出 har:${built}`);
  process.exit(1);
}

let names = [];
try {
  names = execFileSync('tar', ['-tzf', built], { encoding: 'utf8' })
    .split(/\r?\n/)
    .map((n) => n.trim())
    .filter(Boolean);
} catch {
  console.warn('跳过 har 内容校验(未找到可用的 tar)');
}
if (names.length) {
  const abc = names.filter((n) => n.endsWith('.abc'));
  const hasCmake = names.some((n) => n.endsWith('src/main/cpp/CMakeLists.txt'));
  if (abc.length || !hasCmake) {
    console.error(
      `har 内容不符合预期:${abc.length} 个 .abc、CMakeLists.txt ${hasCmake ? '存在' : '缺失'}。`,
    );
    process.exit(1);
  }
}

const dest = path.join(HARMONY_DIR, `${MODULE_NAME}.har`);
fs.copyFileSync(built, dest);

console.log(`\n已生成 ${path.relative(OHOS_DIR, dest)}`);
console.log(`  buildMode=${buildMode}  ${fs.statSync(dest).size} 字节`);