/**
 * 一键安装 / postinstall 成功后的统一终端文案（只读输出）
 */
import { execSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';

export const SKILL_PUBLIC_NAME = '产品设计-体服平台B端-界面生成';
export const PACKAGE_NAME = '@tfdesign/b-end';

function formatDateToMinute(value) {
  if (!value) return null;
  const date = new Date(value);
  if (Number.isNaN(date.getTime())) return null;

  const parts = new Intl.DateTimeFormat('zh-CN', {
    timeZone: 'Asia/Shanghai',
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
  }).formatToParts(date);

  const byType = Object.fromEntries(parts.map((part) => [part.type, part.value]));
  return `${byType.year}-${byType.month}-${byType.day} ${byType.hour}:${byType.minute}`;
}

function readJsonSafe(file) {
  try {
    return JSON.parse(fs.readFileSync(file, 'utf8'));
  } catch {
    return null;
  }
}

export function resolveInstalledVersion(projectRoot, pkgRoot) {
  const candidates = [
    path.join(projectRoot, 'node_modules', '@tfdesign', 'b-end', 'package.json'),
    pkgRoot ? path.join(pkgRoot, 'package.json') : null,
  ].filter(Boolean);

  for (const file of candidates) {
    const pkg = readJsonSafe(file);
    if (pkg?.version) return pkg.version;
  }
  return null;
}

export function resolvePublishedAt(version) {
  if (!version) return null;
  try {
    const out = execSync(`npm view ${PACKAGE_NAME}@${version} time --json`, {
      encoding: 'utf8',
      stdio: ['ignore', 'pipe', 'ignore'],
      timeout: 10_000,
    });
    const data = JSON.parse(out);
    return formatDateToMinute(data?.modified || data?.created);
  } catch {
    return null;
  }
}

export function formatVersionWithDate(version, publishedAt) {
  if (!version) return '';
  if (publishedAt) return `${version}（Skill更新时间 ${publishedAt}）`;
  return version;
}

/**
 * @param {{ projectRoot: string, pkgRoot?: string }} opts
 */
export function printInstallSuccessMessage({ projectRoot, pkgRoot }) {
  const version = resolveInstalledVersion(projectRoot, pkgRoot);
  const publishedAt = resolvePublishedAt(version);
  const versionLabel = formatVersionWithDate(version, publishedAt);
  const versionSuffix = versionLabel ? ` ${versionLabel}` : '';

  console.log('');
  console.log(
    `  已安装Skill：${SKILL_PUBLIC_NAME}${versionSuffix}，适用于体服 B 端后台 / 工作台 / 列表与客服类页面的 React 界面生成。`,
  );
  console.log(
    `  在对话输入 /${SKILL_PUBLIC_NAME} 开始生成（搜不到 Skill 时，重启 IDE 重新打开项目再试）`,
  );
  console.log('');
}
