// 安装 @tfdesign/dashboard 后自动执行：
//  1) IDE Skill 写入（opt-in）
//  2) 入口 CSS 自动补丁：在 @import "tailwindcss" 之后插入 theme.css + Tailwind @source
//  3) 安装报告

import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { isTfdsMonorepoRoot } from './is-tfds-monorepo-root.mjs';
import { runPostinstallTfdsHooks } from './lib/postinstall-tfds-hooks.mjs';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const pkgRoot = path.resolve(__dirname, '..');

const SKILL_PUBLIC_NAME = '产品设计-体服平台数据看板-界面生成';
const LEGACY_SKILL_NAMES = ['dashboard', 'Dashboard', '体服数据看板组件调用SKILL'];
const projectRoot = process.env.INIT_CWD || process.cwd();

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

const projectPkg = readJson(path.join(projectRoot, 'package.json'));
const isSelfPkg = projectPkg?.name === '@tfdesign/dashboard';
const hasNoPkg = !projectPkg;

if (hasNoPkg || isSelfPkg) {
  console.log('\n╔══════════════════════════════════════════════════════╗');
  console.log('║   @tfdesign/dashboard  ⚠ 安装位置需要调整           ║');
  console.log('╚══════════════════════════════════════════════════════╝\n');
  console.log('  请在业务项目根目录执行 npm 安装，或使用一键安装：');
  console.log('    npx -y -p @tfdesign/dashboard@latest tfds-dashboard-setup\n');
  process.exit(0);
}

const skillSrcCandidates = [path.join(pkgRoot, 'skills', SKILL_PUBLIC_NAME)];
const skillSrc = skillSrcCandidates.find((dir) => fs.existsSync(dir)) ?? null;

const REQUIRED_SKILL_FILES = [
  'SKILL.md',
  'DESIGN_PRINCIPLES.md',
  'PAGE_ARCHETYPES.md',
  'components.summary.json',
  'components.index.json',
  'LAYOUT_RECIPES.md',
  'LAYOUT_RULES.md',
  'GLOBAL_DESIGN_RULES.md',
  'CHECKLIST.md',
  'COMMON_FAILURES.md',
];

function readText(p) {
  try {
    return fs.readFileSync(p, 'utf8');
  } catch {
    return '';
  }
}

function hasSourceSkillDiff(dest) {
  return REQUIRED_SKILL_FILES.some((file) => {
    const sourceFile = path.join(skillSrc, file);
    const destFile = path.join(dest, file);
    return readText(sourceFile) !== readText(destFile);
  });
}

function needsSkillRefresh(dest) {
  const missing = REQUIRED_SKILL_FILES.some((file) => !fs.existsSync(path.join(dest, file)));
  if (missing) return true;
  return hasSourceSkillDiff(dest);
}

function copySkillDir(dest) {
  fs.mkdirSync(dest, { recursive: true });
  fs.cpSync(skillSrc, dest, { recursive: true, force: true });
}

const done = [];
const todo = [];

const SKILL_DIR_TARGETS = {
  cursor: { base: path.join(projectRoot, '.cursor', 'skills'), label: `Cursor      Skill → .cursor/skills/${SKILL_PUBLIC_NAME}/  （唤起：/${SKILL_PUBLIC_NAME}）` },
  claude: { base: path.join(projectRoot, '.claude', 'skills'), label: `Claude Code Skill → .claude/skills/${SKILL_PUBLIC_NAME}/  （唤起：/${SKILL_PUBLIC_NAME}）` },
  codex: { base: path.join(projectRoot, '.codex', 'skills'), label: `Codex       参考文件 → .codex/skills/${SKILL_PUBLIC_NAME}/` },
  agents: { base: path.join(projectRoot, '.agents', 'skills'), label: `Agents      Skill → .agents/skills/${SKILL_PUBLIC_NAME}/` },
  traeCn: { base: path.join(projectRoot, '.trae-cn', 'skills'), label: `Trae CN     Skill → .trae-cn/skills/${SKILL_PUBLIC_NAME}/  （Use Skill: ${SKILL_PUBLIC_NAME}）` },
};

function removeLegacySkillDirs(base) {
  for (const name of LEGACY_SKILL_NAMES) {
    const legacy = path.join(base, name);
    if (legacy === path.join(base, SKILL_PUBLIC_NAME) || !fs.existsSync(legacy)) continue;
    try {
      fs.rmSync(legacy, { recursive: true, force: true });
      done.push(`旧 Skill 目录已清理：${path.relative(projectRoot, legacy)}`);
    } catch (e) {
      todo.push(`旧 Skill 目录清理失败：${path.relative(projectRoot, legacy)}（${e?.message || e}）`);
    }
  }
}

function installSkillDir(which) {
  const target = SKILL_DIR_TARGETS[which];
  const dest = path.join(target.base, SKILL_PUBLIC_NAME);
  removeLegacySkillDirs(target.base);

  if (fs.existsSync(dest)) {
    if (needsSkillRefresh(dest)) {
      try {
        copySkillDir(dest);
        done.push(`Skill 已存在且已同步新版（${which}）：${path.relative(projectRoot, dest)}`);
      } catch (e) {
        todo.push(`Skill 同步失败（${which}）：${e?.message || e}`);
      }
    } else {
      done.push(`Skill 已存在且完整，跳过（${which}）：${path.relative(projectRoot, dest)}`);
    }
    return;
  }

  try {
    copySkillDir(dest);
    done.push(target.label);
  } catch (e) {
    todo.push(`Skill 复制失败（${which}）：${e?.message || e}`);
  }
}

function ensureThemeImport(cssPath) {
  const content = readText(cssPath);
  if (!/@import\s+["']tailwindcss["']/.test(content)) return false;
  if (content.includes('@tfdesign/dashboard/theme.css')) return true;

  const lines = content.split('\n');
  const idx = lines.findIndex((line) => /@import\s+["']tailwindcss["']/.test(line));
  const insert = [
    '@import "@tfdesign/dashboard/theme.css";',
    '@source "./**/*.{js,jsx,ts,tsx}";',
    '@source "./node_modules/@tfdesign/dashboard/**/*.{js,jsx}";',
  ];
  lines.splice(idx + 1, 0, ...insert);
  fs.writeFileSync(cssPath, lines.join('\n'), 'utf8');
  return true;
}

function patchCss() {
  if (process.env.SKIP_TFDS_CSS_PATCH === '1') {
    done.push('入口 CSS 补丁已跳过（SKIP_TFDS_CSS_PATCH=1）');
    return;
  }

  const candidates = [
    'src/index.css',
    'src/main.css',
    'src/styles.css',
    'src/global.css',
    'app/globals.css',
    'styles/globals.css',
    'index.css',
  ].map((rel) => path.join(projectRoot, rel));

  const existing = candidates.find((p) => fs.existsSync(p));
  if (!existing) {
    todo.push('未找到入口 CSS 文件（src/index.css / app/globals.css 等）。请手动在 @import "tailwindcss" 之后插入：@import "@tfdesign/dashboard/theme.css"');
    return;
  }

  const ok = ensureThemeImport(existing);
  if (ok) done.push(`入口 CSS 已补齐：${path.relative(projectRoot, existing)}`);
  else todo.push(`入口 CSS 未检测到 @import "tailwindcss"：${path.relative(projectRoot, existing)}（请先补 tailwindcss 入口再重装）`);
}

// Step 1: copy skills (opt-in)
if (!skillSrc) {
  todo.push(`未找到 Skill 源目录：${path.relative(projectRoot, path.join(pkgRoot, 'skills', SKILL_PUBLIC_NAME))}`);
} else if (process.env.SKIP_TFDS_CURSOR_SKILL === '1') {
  done.push('Skill 自动写入已跳过（SKIP_TFDS_CURSOR_SKILL=1）');
} else if (isTfdsMonorepoRoot(projectRoot)) {
  done.push('TFDS 主仓：不在仓库内复制 IDE Skill（请使用 packages/tfds-dashboard/skills/…）');
} else {
  installSkillDir('cursor');
  installSkillDir('claude');
  installSkillDir('codex');
  installSkillDir('agents');
  installSkillDir('traeCn');
}

// Step 2: patch css
patchCss();

runPostinstallTfdsHooks({
  projectRoot,
  pkgRoot,
  packageName: '@tfdesign/dashboard',
  skillName: SKILL_PUBLIC_NAME,
  done,
  todo,
});

// Step 3: report
console.log('\n╔══════════════════════════════════════════════════════╗');
console.log('║     @tfdesign/dashboard 安装后处理报告               ║');
console.log('╚══════════════════════════════════════════════════════╝\n');

for (const line of done) console.log(`  ✓ ${line}`);
if (todo.length > 0) {
  console.log('\n  你可能还需要手动处理：');
  for (const line of todo) console.log(`  ⚠ ${line}`);
}

console.log('\n  使用方式：');
console.log(`    • 输入 /${SKILL_PUBLIC_NAME} 或 Use Skill: ${SKILL_PUBLIC_NAME}`);
console.log('    • 或执行一键安装：npx -y -p @tfdesign/dashboard@latest tfds-dashboard-setup');
console.log('');

