#!/usr/bin/env node
/**
 * 构建 harmony/encrypted_storage.har(在 ohos/.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 = 'encrypted_storage';
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 RNOH_HAR = path.join(
  OHOS_DIR, 'example_auto', 'node_modules', '@react-native-oh',
  'react-native-harmony', 'react_native_openharmony_release.har',
);

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';

function run(cmd, args, cwd) {
  console.log(`\n$ ${cmd} ${args.join(' ')}`);
  execFileSync(isWindows ? `${cmd}.bat` : cmd, args, { cwd, stdio: 'inherit', shell: isWindows });
}

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

if (!fs.existsSync(RNOH_HAR)) {
  console.error(
    `找不到 RNOH release har:${RNOH_HAR}\n` +
    '请先安装 example_auto 依赖:cd ohos/example_auto && npm install --legacy-peer-deps',
  );
  process.exit(1);
}

console.log(`清理 ${path.relative(OHOS_DIR, WRAPPER)}`);
fs.rmSync(WRAPPER, { recursive: true, force: true });
fs.mkdirSync(WRAPPER, { recursive: true });

fs.copyFileSync(RNOH_HAR, path.join(WRAPPER, 'react_native_openharmony_release.har'));

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.ohrn.encryptedstorage.library",
    "vendor": "example",
    "versionCode": 1000000,
    "versionName": "1.0.0"
  }
}
`);

writeJson5('build-profile.json5', `{
  "app": {
    "products": [
      {
        "name": "default",
        "compatibleSdkVersion": "5.0.1(13)",
        "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);

const nodeHarTargets = [
  path.join(OHOS_DIR, 'example_auto', 'node_modules', '@hxa-rn', 'react-native-encrypted-storage', 'harmony', `${MODULE_NAME}.har`),
  path.join(OHOS_DIR, 'example', 'node_modules', '@hxa-rn', 'react-native-encrypted-storage', 'harmony', `${MODULE_NAME}.har`),
];
for (const target of nodeHarTargets) {
  if (fs.existsSync(path.dirname(target))) {
    fs.copyFileSync(built, target);
    console.log(`已同步到 ${path.relative(OHOS_DIR, target)}`);
  }
}

console.log(`\n已生成 ${path.relative(OHOS_DIR, dest)}`);
console.log(`  buildMode=${buildMode}  ${fs.statSync(dest).size} 字节  ${names.filter((n) => !n.endsWith('/')).length} 个文件`);