#!/usr/bin/env node
/**
 * Dashboard 规范接入自检（轻量）
 * - 检查是否安装 @tfdesign/dashboard
 * - 检查入口 CSS 是否引入 theme.css（由 postinstall 自动补丁）
 * - 检查 IDE Skill 是否已同步
 */

import fs from 'node:fs';
import path from 'node:path';

const projectRoot = process.env.INIT_CWD || process.cwd();
const pkgRoot = path.join(projectRoot, 'node_modules', '@tfdesign', 'dashboard');
const SKILL_PUBLIC_NAME = '产品设计-体服平台数据看板-界面生成';

function exists(p) {
  try {
    return fs.existsSync(p);
  } catch {
    return false;
  }
}

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

function findFirstExisting(relCandidates) {
  for (const rel of relCandidates) {
    const abs = path.join(projectRoot, rel);
    if (exists(abs)) return abs;
  }
  return '';
}

console.log('\n╔══════════════════════════════════════════════════════╗');
console.log('║         TFDS Dashboard 接入自检                     ║');
console.log('╚══════════════════════════════════════════════════════╝\n');

if (!exists(pkgRoot)) {
  console.log('✗ 未找到 @tfdesign/dashboard 安装目录。请先执行：');
  console.log('  npm i @tfdesign/dashboard\n');
  process.exit(1);
}
console.log('✓ 已安装 @tfdesign/dashboard');

const cssCandidates = [
  'src/index.css',
  'src/main.css',
  'src/styles.css',
  'src/global.css',
  'app/globals.css',
  'styles/globals.css',
  'index.css',
];
const cssPath = findFirstExisting(cssCandidates);
if (!cssPath) {
  console.log('⚠ 未找到入口 CSS（已跳过 theme.css 检查）。');
} else {
  const css = readText(cssPath);
  if (css.includes('@tfdesign/dashboard/theme.css')) {
    console.log(`✓ 已引入 theme.css：${path.relative(projectRoot, cssPath)}`);
  } else {
    console.log(`⚠ 未检测到 theme.css 引入：${path.relative(projectRoot, cssPath)}`);
    console.log('  你可以手动在 @import "tailwindcss" 之后加一行：');
    console.log('  @import "@tfdesign/dashboard/theme.css";');
  }
}

const skillTargets = [
  path.join(projectRoot, '.cursor', 'skills', SKILL_PUBLIC_NAME, 'SKILL.md'),
  path.join(projectRoot, '.claude', 'skills', SKILL_PUBLIC_NAME, 'SKILL.md'),
  path.join(projectRoot, '.agents', 'skills', SKILL_PUBLIC_NAME, 'SKILL.md'),
  path.join(projectRoot, '.trae-cn', 'skills', SKILL_PUBLIC_NAME, 'SKILL.md'),
];
if (skillTargets.some((p) => exists(p))) {
  console.log(`✓ Skill 已同步：${SKILL_PUBLIC_NAME}`);
} else {
  console.log(`⚠ 未检测到 Skill 同步结果：${SKILL_PUBLIC_NAME}`);
  console.log('  你可以重新执行一次：');
  console.log('  node node_modules/@tfdesign/dashboard/scripts/postinstall-cursor-skill.mjs');
}

console.log('\n──────────────────────────────────────────────────────');
console.log('  自检完成。');
console.log(`  输入 /${SKILL_PUBLIC_NAME} 即可开始生成页面。`);
console.log('──────────────────────────────────────────────────────\n');

