/**
 * 将 PRD、markdownMap 与标注节点说明同步到 annotation-source.json 的 directory.nodes
 */
import { readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';

const __dirname = dirname(fileURLToPath(import.meta.url));
const root = join(__dirname, '..');
const jsonPath = join(root, 'annotation-source.json');
const prdPath = join(root, '.spec/requirements-prd.md');

const doc = JSON.parse(readFileSync(jsonPath, 'utf8'));
const prd = readFileSync(prdPath, 'utf8');
const mm = doc.markdownMap;

doc.markdownMap['lbd-doc-overview'] = `## 1. 模块定位

| 项 | 说明 |
|---|---|
| 模块名称 | 台账数据 — 租赁业务明细 |
| 目标用户 | 业务二部业管 / 运营人员 |
| 核心任务 | 按 Excel 样表维护租赁车辆收入明细、查询汇总、批量导入导出 |
| 页面结构 | 筛选区 + 7 项 KPI + 工具栏 + 48 列宽表（表尾 23 项汇总）+ 分页 |
| 设计基底 | vm-page + ldb-page + lc-page |

对齐 Excel《2026年业务二部运营台账总表》「2.租赁车辆收入明细表」。

---`;

function markdownDoc(id, title) {
  return {
    type: 'markdown',
    id,
    title,
    markdown: mm[id.replace('lbd-doc-', '')] ?? mm[id] ?? doc.data.nodes.find((n) => n.id === id.replace('lbd-doc-', ''))?.annotationText ?? '',
  };
}

/** 目录 markdown 节点：优先 markdownMap 中带 lbd-doc- 前缀的键，否则用标注节点 id */
function nodeDoc(nodeId, title, docId = `lbd-doc-${nodeId}`) {
  const markdown = mm[nodeId] ?? mm[docId] ?? '';
  return { type: 'markdown', id: docId, title, markdown };
}

doc.directory.nodes = [
  {
    type: 'folder',
    id: 'lbd-doc-root',
    title: '租赁业务明细说明',
    defaultExpanded: true,
    children: [
      {
        type: 'markdown',
        id: 'lbd-doc-overview',
        title: '模块总览',
        markdown: doc.markdownMap['lbd-doc-overview'],
      },
      {
        type: 'link',
        id: 'lbd-link-self',
        title: '租赁业务明细原型',
        href: '/prototypes/lease-business-detail',
        target: 'self',
      },
      {
        type: 'markdown',
        id: 'lbd-doc-prd',
        title: 'PRD 全文',
        markdown: prd,
        markdownPath: 'src/prototypes/lease-business-detail/.spec/requirements-prd.md',
      },
      {
        type: 'folder',
        id: 'lbd-doc-page-annotations',
        title: '页面标注',
        defaultExpanded: true,
        children: [
          nodeDoc('lbd-filter', '筛选条件'),
          nodeDoc('lbd-kpi', 'KPI 汇总'),
          nodeDoc('lbd-toolbar', '批量导入导出'),
          nodeDoc('lbd-table', '明细列表'),
          nodeDoc('lbd-changelog-modal', '变更日志'),
        ],
      },
      {
        type: 'folder',
        id: 'lbd-doc-field-annotations',
        title: '字段标注',
        defaultExpanded: false,
        children: [
          nodeDoc('lbd-col-status', '状态'),
          nodeDoc('lbd-col-receivable-total', '应收合计'),
          nodeDoc('lbd-col-outstanding', '未收'),
          nodeDoc('lbd-col-vehicle-actual-cost', '车辆实际成本'),
          nodeDoc('lbd-col-total-cost', '总成本'),
          nodeDoc('lbd-col-profit-loss', '盈亏'),
          nodeDoc('lbd-col-hydrogen-fee', '氢费'),
        ],
      },
      {
        type: 'folder',
        id: 'lbd-doc-specs',
        title: '规格说明',
        defaultExpanded: false,
        children: [
          {
            type: 'markdown',
            id: 'lbd-doc-formulas',
            title: '公式列',
            markdown: mm['lbd-doc-formulas'],
          },
          {
            type: 'markdown',
            id: 'lbd-doc-boundary',
            title: '模块边界',
            markdown: mm['lbd-doc-boundary'],
          },
          {
            type: 'markdown',
            id: 'lbd-doc-source',
            title: '源码入口',
            markdown: `## 8. 源码入口

| 类型 | 路径 |
|---|---|
| 主入口 | \`index.tsx\` |
| 标注源 | \`annotation-source.json\` |
| 列定义 | \`components/tableColumns.ts\` |
| 筛选 / KPI 汇总 | \`utils/detail.ts\` |
| 收款状态 | \`utils/payment-status.ts\` |
| 公式计算 | \`utils/calc-detail.ts\` |
| 导入导出 | \`utils/batch-io.ts\` |
| 变更日志 | \`utils/change-log.ts\` |
| 类型 | \`types.ts\` |
| 组件 | \`FilterPanel.tsx\`、\`DetailKpiRow.tsx\`、\`DetailTable.tsx\`、\`DetailImportModal.tsx\`、\`DetailEditModal.tsx\`、\`DetailChangeLogModal.tsx\` |

---`,
          },
        ],
      },
    ],
  },
];

doc.data.updatedAt = Date.now();
writeFileSync(jsonPath, `${JSON.stringify(doc, null, 2)}\n`, 'utf8');
console.log('Synced directory.nodes with PRD and', doc.data.nodes.length, 'annotation nodes');
