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 fullPrd = fs.readFileSync(path.join(specRoot, 'requirements-prd.md'), 'utf8');
const listPrd = fs.readFileSync(path.join(specRoot, 'requirements-prd-list.md'), 'utf8');
const statementPrd = fs.readFileSync(path.join(specRoot, 'requirements-prd-statement.md'), 'utf8');
const kpiBalanceAlertPrd = fs.readFileSync(path.join(specRoot, 'requirements-prd-kpi-balance-alert.md'), 'utf8');
const scopeMd = fs.readFileSync(path.join(specRoot, 'requirements.md'), 'utf8');

const NODE_DEFS = [
  {
    id: 'h2-site-filter',
    title: '筛选条件',
    pageId: 'site-info',
    color: '#2563eb',
    aiPrompt: '筛选字段与查询/重置行为。',
    annotationText: 'vm 筛选卡片：4 列栅格，标签在上控件在下。',
    locator: {
      selectors: ['.h2-station-page .vm-filter-card', '[data-annotation-id="h2-site-filter"]'],
      fingerprint: 'filter|site-info',
    },
  },
  {
    id: 'h2-site-kpi',
    title: 'KPI 快捷筛选',
    pageId: 'site-info',
    color: '#2563eb',
    aiPrompt: '六张 KPI 卡片口径；预警/欠费点击打开弹窗并支持一键充值。',
    annotationText: '全部 / 签约·普通 / 预付余额预警 / 已欠费 / 无加氢。预警与欠费点击打开站点列表弹窗。',
    locator: {
      selectors: ['.h2-station-page .vm-kpi-row', '[data-annotation-id="h2-site-kpi"]'],
      fingerprint: 'kpi|site-info',
    },
  },
  {
    id: 'h2-site-statement',
    title: '工具栏与对账',
    pageId: 'site-info',
    color: '#d97706',
    aiPrompt: '工具栏操作与对账单氢费联动。',
    annotationText: '全站余额提醒、批量导入、充值单、新建站点；对账回写车辆氢费明细。',
    locator: {
      selectors: ['.h2-station-page .vm-table-toolbar', '[data-annotation-id="h2-site-toolbar"]'],
      fingerprint: 'toolbar|statement',
    },
  },
  {
    id: 'h2-site-table',
    title: '站点列表',
    pageId: 'site-info',
    color: '#32a06e',
    aiPrompt: '台账表格列、下钻与行内操作。',
    annotationText: '名称、营业、成本价、加氢量、预付余额、更多菜单。',
    locator: {
      selectors: ['.h2-station-page .vm-table-card', '[data-annotation-id="h2-site-table"]'],
      fingerprint: 'table|site-info',
    },
  },
  {
    id: 'h2-site-price-cost-input',
    title: '成本价格输入',
    pageId: 'site-info',
    color: '#d97706',
    aiPrompt: '固定价格规则适用客户与成本单价录入。',
    annotationText: '选择全部客户时：第一权重取单站单客户价格配置，第二权重取本条全部客户价格配置',
    locator: {
      selectors: ['[data-annotation-id="h2-site-price-cost-input"]'],
      fingerprint: 'input|price-cost',
    },
  },
  {
    id: 'h2-site-price-tiered',
    title: '阶梯价格',
    pageId: 'site-info',
    color: '#7c3aed',
    aiPrompt: '阶梯价格取价、累计加氢量与重置日期逻辑。',
    annotationText: '阶梯区间内展示对应成本价；达下一档按新价；重置日累计量归零重新计档；生效时间不追溯历史',
    locator: {
      selectors: ['[data-annotation-id="h2-site-price-tiered"]'],
      fingerprint: 'radio|price-tiered',
    },
  },
  {
    id: 'h2-site-statement-form',
    title: '生成对账单',
    pageId: 'site-info',
    color: '#7c3aed',
    aiPrompt: '选期拉取氢费明细、二次确认与结算提交逻辑。',
    annotationText: '选日期拉取站点加氢记录；生成前二次确认；提交后明细锁定为已对账',
    locator: {
      selectors: ['[data-annotation-id="h2-site-statement-form"]', '.h2-statement-form-wrap'],
      fingerprint: 'form|statement',
    },
  },
];

const NODE_PRD_MAP = {
  'h2-site-filter': { file: 'list', heading: '## 2. 筛选区' },
  'h2-site-kpi': { file: 'list', heading: '## 3. KPI 统计卡片' },
  'h2-site-statement': { file: 'list', heading: '## 4. 列表工具栏', combine: ['## 4. 列表工具栏', '## 6. 数据来源'] },
  'h2-site-table': { file: 'list', heading: '## 5. 列表字段说明' },
  'h2-site-price-cost-input': { file: 'full', heading: '### 5.2 价格配置' },
  'h2-site-price-tiered': { file: 'full', heading: '#### 阶梯价格 · 生成逻辑' },
  'h2-site-statement-form': { file: 'statement', heading: '#### 生成对账单 · 业务逻辑' },
};

const prdByKey = { list: listPrd, statement: statementPrd, full: fullPrd };

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

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 body = extractFromPrd(mapping);
    if (body) return body;
  }
  if (node.id === 'h2-site-statement') {
    const toolbar = extractSection(listPrd, '## 4. 列表工具栏');
    const stmt = extractSection(statementPrd, '## 1. 数据来源');
    if (toolbar && stmt) return `${toolbar}\n\n---\n\n${stmt}`;
  }
  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: { ...def.locator, path: [] },
  aiPrompt: def.aiPrompt,
  annotationText: def.annotationText,
  hasMarkdown: true,
  color: def.color,
  images: [],
  createdAt: now,
  updatedAt: now,
  controls: [],
}));

const markdownMap = Object.fromEntries(nodes.map((node) => [node.id, buildNodeMarkdown(node)]));

const overviewMd = [
  '## 1. 模块定位',
  '',
  '| 项 | 说明 |',
  '|---|---|',
  '| 模块 | 加氢站管理 → 站点信息 |',
  '| 用户 | 运营、财务结算、管理员 |',
  '| 核心任务 | 站点主数据、运营配置、氢费对账结算 |',
  '| 页面结构 | 筛选 + KPI + 工具栏 + 列表 + 分页 |',
  '',
  '## 2. 关联模块',
  '',
  '- **车辆氢费明细**：氢费数据来源与对账回写目标',
  '- **加氢站合包**：加氢订单、加氢记录仍在合包入口',
  '',
  '## 3. 验收重点',
  '',
  '1. KPI 预付余额预警/已欠费口径与点击弹窗、批量充值一致',
  '2. 对账单两阶段流程与跨页回写',
  '3. 列表布局与租赁合同 vm 规范一致',
].join('\n');

const acceptanceMd = extractSection(fullPrd, '## 8. 验收标准') ?? '## 验收标准\n\n见 PRD 全文。';

const source = {
  documentVersion: 1,
  format: 'axhub-annotation-source',
  data: {
    version: 2,
    prototypeName: 'oneos-web-h2-station-site',
    pageId: 'site-info',
    updatedAt: now,
    nodes,
  },
  markdownMap,
  assetMap: {},
  directory: {
    nodes: [
      {
        type: 'folder',
        id: 'h2-site-doc-root',
        title: '站点信息说明',
        defaultExpanded: true,
        children: [
          {
            type: 'markdown',
            id: 'h2-site-doc-overview',
            title: '模块总览',
            markdown: overviewMd,
          },
          {
            type: 'link',
            id: 'h2-site-link-vh2',
            title: '车辆氢费明细',
            href: '/prototypes/vehicle-h2-fee-ledger',
            target: 'self',
          },
          {
            type: 'link',
            id: 'h2-site-link-bundle',
            title: '加氢站管理（合包）',
            href: '/prototypes/oneos-web-h2-station',
            target: 'self',
          },
          {
            type: 'folder',
            id: 'h2-site-doc-prd',
            title: 'PRD 全文',
            defaultExpanded: true,
            children: [
              {
                type: 'markdown',
                id: 'h2-site-doc-prd-full',
                title: 'PRD 完整文档',
                markdown: fullPrd,
                markdownPath: 'src/prototypes/oneos-web-h2-station-site/.spec/requirements-prd.md',
              },
              {
                type: 'markdown',
                id: 'h2-site-doc-prd-list',
                title: '列表页 PRD',
                markdown: listPrd,
                markdownPath: 'src/prototypes/oneos-web-h2-station-site/.spec/requirements-prd-list.md',
              },
              {
                type: 'markdown',
                id: 'h2-site-doc-prd-kpi-balance',
                title: '预付余额 KPI 交互',
                markdown: kpiBalanceAlertPrd,
                markdownPath: 'src/prototypes/oneos-web-h2-station-site/.spec/requirements-prd-kpi-balance-alert.md',
              },
              {
                type: 'markdown',
                id: 'h2-site-doc-prd-statement',
                title: '对账与结算 PRD',
                markdown: statementPrd,
                markdownPath: 'src/prototypes/oneos-web-h2-station-site/.spec/requirements-prd-statement.md',
              },
              {
                type: 'markdown',
                id: 'h2-site-doc-scope',
                title: '范围与决策',
                markdown: scopeMd,
                markdownPath: 'src/prototypes/oneos-web-h2-station-site/.spec/requirements.md',
              },
              {
                type: 'markdown',
                id: 'h2-site-doc-acceptance',
                title: '验收标准',
                markdown: acceptanceMd,
              },
            ],
          },
          {
            type: 'folder',
            id: 'h2-site-doc-page',
            title: '页面标注',
            defaultExpanded: true,
            children: nodes.map((node) => ({
              type: 'markdown',
              id: `h2-site-doc-node-${node.id}`,
              title: node.title,
              markdown: markdownMap[node.id],
            })),
          },
        ],
      },
    ],
  },
};

const outPath = path.join(protoRoot, 'annotation-source.json');
fs.writeFileSync(outPath, `${JSON.stringify(source, null, 2)}\n`, 'utf8');
console.log(`Wrote ${outPath} (${nodes.length} nodes, ${Object.keys(markdownMap).length} markdown entries)`);
