import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = path.dirname(fileURLToPath(import.meta.url));
const protoRoot = path.resolve(__dirname, '..');
const prd = fs.readFileSync(path.join(protoRoot, '.spec/requirements-prd.md'), 'utf8');

const NODE_DEFS = [
  { id: 'sob-filter', title: '筛选条件', color: '#2563eb', aiPrompt: '月份、出车日期、业务、车牌等筛选。', annotationText: '默认 4 项，可展开；主管可见维护人。' },
  { id: 'sob-kpi', title: 'KPI 统计', color: '#64748b', aiPrompt: '六张统计卡片口径。', annotationText: '金额、成本、氢费、ETC、盈亏汇总。' },
  { id: 'sob-toolbar', title: '列表工具栏', color: '#0f766e', aiPrompt: '导入、导出、批量删除、添加行。', annotationText: '' },
  { id: 'sob-table', title: '自营台账宽表', color: '#2563eb', aiPrompt: '出车记录与费用明细。', annotationText: '盈亏按金额减总成本展示。' },
];

function extractSection(md, heading) {
  const lines = md.split('\n');
  const start = lines.findIndex((line) => line.startsWith(heading));
  if (start < 0) return null;
  const level = heading.match(/^#+/)?.[0].length ?? 2;
  let end = lines.length;
  for (let i = start + 1; i < lines.length; i++) {
    if (/^#{1,6}\s/.test(lines[i])) {
      const l = lines[i].match(/^#+/)?.[0].length ?? 2;
      if (l <= level) { end = i; break; }
    }
  }
  return lines.slice(start, end).join('\n').trim();
}

const map = {
  'sob-filter': '## 2. 筛选区',
  'sob-kpi': '## 3. KPI 统计卡片（6 张）',
  'sob-toolbar': '## 4. 列表工具栏',
  'sob-table': '## 5. 列表字段（核心列）',
};

const nodes = NODE_DEFS.map((def, index) => ({
  id: def.id,
  index: index + 1,
  title: def.title,
  pageId: 'list',
  locator: { selectors: [`[data-annotation-id="${def.id}"]`], fingerprint: def.id, path: [] },
  aiPrompt: def.aiPrompt,
  annotationText: def.annotationText,
  hasMarkdown: true,
  color: def.color,
  images: [],
  createdAt: 1740787200000,
  updatedAt: 1740787200000,
}));

const markdownMap = Object.fromEntries(
  nodes.map((node) => [node.id, extractSection(prd, map[node.id]) ?? `# ${node.title}\n\n${node.aiPrompt}`]),
);

const source = {
  documentVersion: 1,
  format: 'axhub-annotation-source',
  data: {
    version: 2,
    prototypeName: 'self-operated-business-ledger',
    pageId: 'list',
    updatedAt: Date.now(),
    nodes,
  },
  markdownMap,
  assetMap: {},
  directory: {
    nodes: [{
      type: 'folder',
      id: 'sob-doc-root',
      title: '自营业务台账说明',
      defaultExpanded: true,
      children: [
        { type: 'markdown', id: 'sob-doc-overview', title: '模块总览', markdown: extractSection(prd, '## 1. 模块定位') ?? prd },
        { type: 'link', id: 'sob-link-self', title: '自营业务台账原型', href: '/prototypes/self-operated-business-ledger', target: 'self' },
        { type: 'markdown', id: 'sob-doc-prd', title: 'PRD 全文', markdown: prd },
        ...nodes.map((node) => ({
          type: 'markdown',
          id: `sob-doc-${node.id}`,
          title: node.title,
          markdown: markdownMap[node.id],
        })),
      ],
    }],
  },
};

fs.writeFileSync(path.join(protoRoot, 'annotation-source.json'), `${JSON.stringify(source, null, 2)}\n`);
console.log(`Built annotation-source.json with ${nodes.length} nodes.`);
