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 listPrd = fs.readFileSync(path.join(protoRoot, '.spec/requirements-prd-list.md'), 'utf8');
const createPrd = fs.readFileSync(path.join(protoRoot, '.spec/requirements-prd-create.md'), 'utf8');

const NODE_DEFS = [
  { id: 'cm-list-filter', title: '筛选条件', pageId: 'list', color: '#2563eb', aiPrompt: '列表筛选区字段与查询逻辑。', annotationText: '默认展示 4 项（一行），点击「更多筛选」显示全部。' },
  { id: 'cm-risk-role-switch', title: '操作角色切换', pageId: 'list', color: '#64748b', aiPrompt: '模拟 8 类角色（销售/法务/财务/业管/运维/风控/管理层/管理员），驱动分区打标与审批权限。', annotationText: '切换角色后 Drawer 分区维护、可选标签、审批与脱敏规则联动更新。' },
  { id: 'cm-risk-kpi-cards', title: '风险 KPI 卡片', pageId: 'list', color: '#059669', aiPrompt: '按风险类型快速筛选客户列表。', annotationText: '5 张卡片：全部客户、有风险客户、财务风险、法务风险、业管风险。' },
  { id: 'cm-list-toolbar', title: '列表工具栏', pageId: 'list', color: '#0f766e', aiPrompt: '新增、导入、导出、批量打标入口。', annotationText: '勾选客户后显示「批量打标」。' },
  { id: 'cm-list-table', title: '客户台账列表', pageId: 'list', color: '#2563eb', aiPrompt: '客户台账表格列与行操作，含风险标签列。', annotationText: '操作列含「管理标签」；标签列按风险级别着色。' },
  { id: 'cm-risk-tag-drawer', title: '风险标签抽屉', pageId: 'list', color: '#d97706', aiPrompt: '单客户打标、法务工作台待办、审批、解除申请与审批、日志。', annotationText: '打标时间/下次复核时间只读；解除说明按标签类型区分（法务含查验提示，财务/业管不含）。' },
  { id: 'cm-batch-risk-tag-btn', title: '批量打标入口', pageId: 'list', color: '#0f766e', aiPrompt: '勾选多客户后批量提交同一标签。', annotationText: '' },
  { id: 'cm-batch-risk-tag-modal', title: '批量打标弹窗', pageId: 'list', color: '#0f766e', aiPrompt: '批量打标表单与提交逻辑。', annotationText: '' },
  { id: 'cm-create-base', title: '客户信息', pageId: 'create', color: '#2563eb', aiPrompt: '客户类型、全称、城市、部门负责人、合作状态等。', annotationText: '通讯地址自动识别省市；合作状态四选一；不含风险标签字段。' },
  { id: 'cm-create-contact', title: '联系人信息', pageId: 'create', color: '#64748b', aiPrompt: '联系人姓名、手机、职位。', annotationText: '均为选填。' },
  { id: 'cm-create-invoice', title: '付款及开票信息', pageId: 'create', color: '#d97706', aiPrompt: '发票抬头、税号、银行账号等。', annotationText: '发票抬头只读，与客户全称一致。' },
  { id: 'cm-create-footer', title: '底部操作栏', pageId: 'create', color: '#0f766e', aiPrompt: '重置与提交。', annotationText: '提交校验必填项后 Toast 并返回列表。' },
];

const prdByKey = { list: listPrd, create: createPrd };

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

function extractFromPrd({ prd, heading, sub }) {
  const md = prdByKey[prd];
  if (!md) return null;
  const base = extractSection(md, heading);
  if (!base) return null;
  if (!sub) return base;
  return extractSection(base, sub) ?? base;
}

const NODE_PRD_MAP = {
  'cm-list-filter': { prd: 'list', heading: '## 4. 筛选区' },
  'cm-risk-role-switch': { prd: 'list', heading: '## 6. 列表工具栏', sub: '### 6.1 操作角色切换（原型演示）' },
  'cm-risk-kpi-cards': { prd: 'list', heading: '## 5. 风险 KPI 卡片筛选' },
  'cm-list-toolbar': { prd: 'list', heading: '## 6. 列表工具栏' },
  'cm-list-table': { prd: 'list', heading: '## 7. 列表字段说明' },
  'cm-risk-tag-drawer': { prd: 'list', heading: '## 9. 风险标签维护（列表页专属）' },
  'cm-batch-risk-tag-btn': { prd: 'list', heading: '## 9. 风险标签维护（列表页专属）', sub: '### 9.1 入口' },
  'cm-batch-risk-tag-modal': { prd: 'list', heading: '## 9. 风险标签维护（列表页专属）', sub: '### 9.5 批量打标' },
  'cm-create-base': { prd: 'create', heading: '## 2. 客户信息' },
  'cm-create-contact': { prd: 'create', heading: '## 3. 联系人信息' },
  'cm-create-invoice': { prd: 'create', heading: '## 4. 付款及开票信息' },
  'cm-create-footer': { prd: 'create', heading: '## 5. 校验与提交' },
};

function buildFallbackMarkdown(node) {
  const parts = [`# ${node.title}`, ''];
  if (node.aiPrompt) parts.push(node.aiPrompt, '');
  if (node.annotationText?.trim()) parts.push('## 说明', '', node.annotationText.trim());
  return parts.join('\n').trim();
}

function buildNodeMarkdown(node) {
  const mapping = NODE_PRD_MAP[node.id];
  if (mapping) {
    const prdBody = extractFromPrd(mapping);
    if (prdBody) return prdBody;
  }
  return buildFallbackMarkdown(node);
}

const now = Date.now();
const nodes = NODE_DEFS.map((def, index) => ({
  id: def.id,
  index: index + 1,
  title: def.title,
  pageId: def.pageId,
  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, buildNodeMarkdown(node)]));

const listPageNodes = nodes.filter((n) => n.pageId === 'list');
const createPageNodes = nodes.filter((n) => n.pageId === 'create');

const source = {
  documentVersion: 1,
  format: 'axhub-annotation-source',
  data: {
    version: 2,
    prototypeName: 'customer-management',
    pageId: 'list',
    updatedAt: now,
    nodes,
  },
  markdownMap,
  assetMap: {},
  directory: {
    nodes: [
      {
        type: 'folder',
        id: 'cm-doc-root',
        title: '客户管理说明',
        defaultExpanded: true,
        children: [
          {
            type: 'markdown',
            id: 'cm-doc-overview',
            title: '模块总览',
            markdown: extractSection(listPrd, '## 1. 模块定位') ?? '# 客户管理',
          },
          {
            type: 'link',
            id: 'cm-link-self',
            title: '客户管理原型',
            href: '/prototypes/customer-management',
            target: 'self',
          },
          {
            type: 'folder',
            id: 'cm-doc-prd',
            title: 'PRD 全文',
            defaultExpanded: false,
            children: [
              { type: 'markdown', id: 'cm-doc-prd-list', title: '列表页 PRD', markdown: listPrd },
              { type: 'markdown', id: 'cm-doc-prd-create', title: '新增页 PRD', markdown: createPrd },
            ],
          },
          {
            type: 'folder',
            id: 'cm-doc-list',
            title: '列表页模块',
            defaultExpanded: true,
            children: [
              {
                type: 'route',
                id: 'cm-route-list',
                title: '打开列表页',
                route: 'customer-management:list',
                payload: { pageId: 'list' },
              },
              ...listPageNodes.map((node) => ({
                type: 'markdown',
                id: `cm-doc-node-${node.id}`,
                title: node.title,
                markdown: markdownMap[node.id],
              })),
            ],
          },
          {
            type: 'folder',
            id: 'cm-doc-create',
            title: '新增页模块',
            defaultExpanded: true,
            children: [
              {
                type: 'route',
                id: 'cm-route-create',
                title: '打开新增页',
                route: 'customer-management:create',
                payload: { pageId: 'create' },
              },
              ...createPageNodes.map((node) => ({
                type: 'markdown',
                id: `cm-doc-node-${node.id}`,
                title: node.title,
                markdown: markdownMap[node.id],
              })),
            ],
          },
        ],
      },
    ],
  },
};

fs.writeFileSync(
  path.join(protoRoot, 'annotation-source.json'),
  `${JSON.stringify(source, null, 2)}\n`,
  'utf8',
);

console.log(`Built annotation-source.json with ${nodes.length} nodes.`);
