import fs from 'node:fs';
import path from 'node:path';
import { spawnSync } from 'node:child_process';
import { writeTfdsLockEntry } from './tfds-lock.mjs';

/**
 * postinstall 收尾：写入 .tfds/lock.json + 可选版本检测
 *
 * @param {object} options
 * @param {string} options.projectRoot
 * @param {string} options.pkgRoot
 * @param {string} options.packageName
 * @param {string} options.skillName
 * @param {string[]} [options.done]
 * @param {string[]} [options.todo]
 */
export function runPostinstallTfdsHooks({
  projectRoot,
  pkgRoot,
  packageName,
  skillName,
  done = [],
  todo = [],
}) {
  let localVersion = null;
  try {
    localVersion = JSON.parse(fs.readFileSync(path.join(pkgRoot, 'package.json'), 'utf8')).version;
  } catch {
    todo.push('未能读取包版本，跳过 .tfds/lock.json 写入');
    return;
  }

  try {
    const lockPath = writeTfdsLockEntry({
      projectRoot,
      packageName,
      skillName,
      version: localVersion,
    });
    done.push(`版本锁已写入：${path.relative(projectRoot, lockPath)}（v ${localVersion}）`);
  } catch (error) {
    todo.push(`版本锁写入失败：${error?.message || error}`);
  }

  if (process.env.SKIP_TFDS_UPDATE_CHECK === '1') {
    done.push('版本更新检测已跳过（SKIP_TFDS_UPDATE_CHECK=1）');
    return;
  }

  const updateCheckScript = path.join(pkgRoot, 'scripts', 'check-tfds-update.mjs');
  if (!fs.existsSync(updateCheckScript)) {
    todo.push('未找到 check-tfds-update.mjs，已跳过版本检测');
    return;
  }

  const result = spawnSync(process.execPath, [updateCheckScript], {
    cwd: projectRoot,
    stdio: 'inherit',
    env: {
      ...process.env,
      TFDS_PROJECT_ROOT: projectRoot,
    },
  });

  if (result.error) {
    todo.push(`版本更新检测未完成：${result.error.message}`);
    return;
  }

  if (result.status === 1) {
    todo.push('检测到 npm 有新版本（详见上方输出）。生成页面前建议先升级，或明确选择继续用当前版本。');
  }
}
