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 specRoot = path.join(protoRoot, '.spec');
const resourcesPrd = path.resolve(protoRoot, '../../resources/lease-contract-management/PRD.md');

const listPrd = fs.readFileSync(path.join(specRoot, 'requirements-prd-list.md'), 'utf8');
const createPrd = fs.readFileSync(path.join(specRoot, 'requirements-prd-create.md'), 'utf8');
const fullPrd = fs.readFileSync(resourcesPrd, 'utf8');

const NODE_DEFS = [
  { id: 'lc-list-filter', title: '筛选条件', pageId: 'list', color: '#2563eb', aiPrompt: '列表筛选区字段与查询逻辑。', annotationText: '默认展示 4 项，可展开至 12 项；查询与 KPI 联动。' },
  { id: 'lc-list-kpi', title: 'KPI 统计卡片', pageId: 'list', color: '#64748b', aiPrompt: '五张 KPI 卡片口径与点击筛选。', annotationText: '全部 / 进行中 / 已终止 / 临期 / 过期。' },
  { id: 'lc-fleet-summary', title: '在租车辆概览', pageId: 'list', color: '#32a06e', aiPrompt: '按品牌型号统计在租车辆，支持品牌标签筛选。', annotationText: '顶部展示在租总数；品牌标签筛选车型卡片；点击卡片查看车辆明细。' },
  { id: 'lc-list-toolbar', title: '列表工具栏', pageId: 'list', color: '#0f766e', aiPrompt: '费用模板、导出、新增入口。', annotationText: '「新增」进入租赁合同创建页。' },
  { id: 'lc-list-table', title: '合同台账列表', pageId: 'list', color: '#2563eb', aiPrompt: '台账表格列与操作。', annotationText: '' },
  { id: 'lc-create-main-contract', title: '主体合同信息', pageId: 'create', color: '#32a06e', aiPrompt: '签约、里程、费用三块表单。', annotationText: '完成度徽章；甲乙档案只读同步。' },
  { id: 'lc-create-lease-order', title: '附件1：租赁订单', pageId: 'create', color: '#2563eb', aiPrompt: '订单车辆与交车信息。', annotationText: '三者责任险等为完成度必填项。' },
  { id: 'lc-create-poa', title: '授权委托书', pageId: 'create', color: '#7c3aed', aiPrompt: '受托人列表编辑。', annotationText: '至少一行且姓名/联系方式/身份证完整。' },
  { id: 'lc-create-preview', title: '实时预览', pageId: 'create', color: '#0ea5e9', aiPrompt: 'Word 版式预览与可编辑正文。', annotationText: '改动风控红线条款将触发非标准合同。' },
  { id: 'lc-create-footer', title: '底栏操作', pageId: 'create', color: '#64748b', aiPrompt: '取消、保存草稿、提交审核。', annotationText: '保存/提交时展示将走的审批类型。' },
];

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, combine }) {
  const md = prdByKey[prd];
  if (!md) return null;
  if (combine?.length) {
    return combine.map((h) => extractSection(md, h)).filter(Boolean).join('\n\n---\n\n') || null;
  }
  const base = extractSection(md, heading);
  if (!base) return null;
  if (!sub) return base;
  return extractSection(base, sub) ?? base;
}

const NODE_PRD_MAP = {
  'lc-list-filter': { prd: 'list', heading: '## 4. 筛选区' },
  'lc-list-kpi': { prd: 'list', heading: '## 5. KPI 统计卡片' },
  'lc-list-toolbar': { prd: 'list', heading: '## 6. 列表工具栏' },
  'lc-list-table': { prd: 'list', heading: '## 7. 列表字段说明', combine: ['## 7. 列表字段说明', '## 8. 操作与弹窗'] },
  'lc-create-main-contract': { prd: 'create', heading: '## 2. 主体合同信息' },
  'lc-create-lease-order': { prd: 'create', heading: '## 3. 附件1：租赁订单' },
  'lc-create-poa': { prd: 'create', heading: '## 4. 授权委托书' },
  'lc-create-preview': { prd: 'create', heading: '## 5. 实时预览', combine: ['## 5. 实时预览', '## 6. 审批类型判定'] },
  'lc-create-footer': { prd: 'create', heading: '## 7. 底栏操作' },
};


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 overviewMd = extractSection(fullPrd, '## 1. 背景与目标') ?? '# 租赁合同管理';

const source = {
  documentVersion: 1,
  format: 'axhub-annotation-source',
  data: {
    version: 2,
    prototypeName: 'lease-contract-management',
    pageId: 'list',
    updatedAt: now,
    nodes,
  },
  markdownMap,
  assetMap: {},
  directory: {
    nodes: [
      {
        type: 'folder',
        id: 'lc-doc-root',
        title: '租赁合同管理说明',
        defaultExpanded: true,
        children: [
          {
            type: 'markdown',
            id: 'lc-doc-overview',
            title: '模块总览',
            markdown: overviewMd,
          },
          {
            type: 'link',
            id: 'lc-link-template',
            title: '合同模板管理',
            href: '/prototypes/contract-template-management',
            target: 'self',
          },
          {
            type: 'folder',
            id: 'lc-doc-prd',
            title: 'PRD 全文',
            defaultExpanded: true,
            children: [
              {
                type: 'markdown',
                id: 'lc-doc-prd-full',
                title: 'PRD 完整文档',
                markdown: fullPrd,
                markdownPath: 'src/resources/lease-contract-management/PRD.md',
              },
              {
                type: 'markdown',
                id: 'lc-doc-prd-list',
                title: '列表页 PRD',
                markdown: listPrd,
                markdownPath: 'src/prototypes/lease-contract-management/.spec/requirements-prd-list.md',
              },
              {
                type: 'markdown',
                id: 'lc-doc-prd-create',
                title: '新增页 PRD',
                markdown: createPrd,
                markdownPath: 'src/prototypes/lease-contract-management/.spec/requirements-prd-create.md',
              },
              {
                type: 'markdown',
                id: 'lc-doc-prd-acceptance',
                title: '验收标准',
                markdown: extractSection(fullPrd, '## 12. 验收标准') ?? '## 验收标准',
              },
            ],
          },
          {
            type: 'folder',
            id: 'lc-doc-list',
            title: '列表页模块',
            defaultExpanded: true,
            children: [
              {
                type: 'route',
                id: 'lc-route-list',
                title: '打开列表页',
                route: 'lease-contract:list',
                payload: { pageId: 'list' },
              },
              ...listPageNodes.map((node) => ({
                type: 'markdown',
                id: `lc-doc-node-${node.id}`,
                title: node.title,
                markdown: markdownMap[node.id],
              })),
            ],
          },
          {
            type: 'folder',
            id: 'lc-doc-create',
            title: '新增页模块',
            defaultExpanded: false,
            children: [
              {
                type: 'route',
                id: 'lc-route-create',
                title: '打开新增页',
                route: 'lease-contract:create',
                payload: { pageId: 'create' },
              },
              ...createPageNodes.map((node) => ({
                type: 'markdown',
                id: `lc-doc-node-${node.id}`,
                title: node.title,
                markdown: markdownMap[node.id],
              })),
            ],
          },
          {
            type: 'markdown',
            id: 'lc-doc-annotation-hint',
            title: '标注查看提示',
            markdown: '## 标注查看提示\n\n右侧标注工具栏可浏览目录、切换主题与颜色筛选。列表页与新增页标注按当前页面自动显隐。\n\n**PRD 同步**：修改 `src/resources/lease-contract-management/PRD.md` 或 `.spec/requirements-prd-*.md` 后，运行 `node src/prototypes/lease-contract-management/scripts/build-annotation-source.mjs` 重新生成 `annotation-source.json`。',
          },
        ],
      },
    ],
  },
};

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.`);
