import fs from 'node:fs';
import path from 'node:path';
import { createHash } from 'node:crypto';

export const REQUIRED_REPORTS = Object.freeze(['docs/RESEARCH.md', 'docs/research/CURSOR-MECHANISMS.md', 'docs/research/CONTEXT-RECOVERY.md', 'docs/research/TOOL-LOOP.md']);
const hash = bytes => createHash('sha256').update(bytes).digest('hex');
const simple = value => value.replaceAll('\\', '/');

export function createDocumentationBundle({ root, portableRoot, evidenceRoot, archiveName, sourceCommit }) {
  if (!/^[a-f0-9]{40}$/.test(sourceCommit) || !/^[A-Za-z0-9._-]+\.zip$/.test(archiveName)) throw new Error('Documentation needs the fixed source commit and separate archive name.');
  if (fs.existsSync(evidenceRoot)) throw new Error('Historical evidence output must be a new directory.');
  const entries = [];
  const walk = relative => {
    for (const entry of fs.readdirSync(path.join(root, relative), { withFileTypes: true })) {
      const next = path.posix.join(relative, entry.name);
      if (entry.isSymbolicLink()) throw new Error('Documentation source cannot contain links: ' + next);
      if (entry.isDirectory()) walk(next);
      else if (entry.isFile()) {
        const bytes = fs.readFileSync(path.join(root, next));
        entries.push({ path: next, bytes: bytes.length, sha256: hash(bytes) });
      } else throw new Error('Documentation source must contain regular files: ' + next);
    }
  };
  walk('docs'); entries.sort((a, b) => a.path.localeCompare(b.path));
  const byPath = new Map(entries.map(row => [row.path, row]));
  for (const file of REQUIRED_REPORTS) if (!byPath.has(file)) throw new Error('Required original research report missing: ' + file);
  // Text guides and original research remain offline. Large historical raw
  // receipts/screenshots are independently shipped with their original paths.
  const selected = new Set(entries.filter(row => /^docs\/[^/]+\.md$/.test(row.path) || /^docs\/research\/[^/]+\.(?:md|json)$/.test(row.path)).map(row => row.path));
  const references = [], shipped = [];
  fs.mkdirSync(evidenceRoot, { recursive: true });
  for (const row of entries) {
    const target = path.join(evidenceRoot, row.path); fs.mkdirSync(path.dirname(target), { recursive: true });
    fs.copyFileSync(path.join(root, row.path), target);
    if (hash(fs.readFileSync(target)) !== row.sha256) throw new Error('Original evidence copy differs: ' + row.path);
  }
  const evidenceManifest = { schema: 1, app: 'agent-workbench-evidence', sourceCommit, scope: 'Original docs tree, including all successful/failed historical evidence. No runtime execution dependency.', files: entries };
  const evidenceBytes = Buffer.from(JSON.stringify(evidenceManifest, null, 2) + '\n');
  fs.writeFileSync(path.join(evidenceRoot, 'MANIFEST.json'), evidenceBytes, { flag: 'wx' });
  const rewrite = (file, original) => original.replace(/\]\(([^)]+)\)/g, (whole, raw) => {
    const [target] = raw.split('#');
    if (!target || /^[a-z]+:/i.test(target) || target.startsWith('/')) return whole;
    let decoded;
    try { decoded = decodeURI(target); } catch { references.push({ from: file, target, disposition: 'malformed-historical-reference' }); return whole; }
    const resolved = simple(path.posix.normalize(path.posix.join(path.posix.dirname(file), decoded)));
    if (!resolved.startsWith('docs/')) return whole;
    const source = byPath.get(resolved);
    if (!source) {
      references.push({ from: file, target, disposition: 'historical-source-not-in-repository' });
      return whole;
    }
    if (selected.has(resolved)) return whole;
    references.push({ from: file, target: resolved, sha256: source.sha256, disposition: REQUIRED_REPORTS.includes(file) ? 'original-report-reference-in-evidence-archive' : 'evidence-catalog-link' });
    if (REQUIRED_REPORTS.includes(file)) return whole; // Preserve all four original report bytes exactly.
    const catalogue = path.posix.relative(path.posix.dirname(file), 'docs/EVIDENCE-CATALOG.md');
    return '](' + catalogue + '#e-' + source.sha256.slice(0, 16) + ')';
  });
  for (const file of [...selected, 'README.md']) {
    const original = fs.readFileSync(path.join(root, file));
    const content = Buffer.from(rewrite(file, original.toString('utf8')));
    const destination = path.join(portableRoot, file); fs.mkdirSync(path.dirname(destination), { recursive: true });
    fs.writeFileSync(destination, content);
    shipped.push({ path: file, bytes: content.length, sha256: hash(content), sourceSha256: hash(original), originalBytesPreserved: content.equals(original) });
  }
  const linked = new Map(references.filter(row => row.sha256).map(row => [row.target, byPath.get(row.target)]));
  const catalogue = ['# 历史验收资料', '', '运行包保留离线使用说明和四份原研究报告。完整历史原件另存于配套证据包，包含原路径、SHA-256、成功与失败记录；源码包也保留完整资料。', '',
    `配套归档：\`${archiveName}\``, '', `原件清单 SHA-256：\`${hash(evidenceBytes)}\``, '',
    '请将证据包解压到单独目录，按其中的原 docs/ 路径查看。不要解压到受完整性核对的程序目录。缺少证据包不影响运行工作台。', ''];
  for (const [file, row] of [...linked].sort(([a], [b]) => a.localeCompare(b))) catalogue.push(`<a id="e-${row.sha256.slice(0, 16)}"></a>`, `## ${file}`, '', `原件：\`${file}\` · ${row.bytes} 字节`, '', `SHA-256：\`${row.sha256}\``, '');
  fs.writeFileSync(path.join(portableRoot, 'docs/EVIDENCE-CATALOG.md'), catalogue.join('\n'));
  const result = { schema: 1, sourceCommit, archiveName, evidenceManifestSha256: hash(evidenceBytes), originalFiles: entries.length, originalBytes: entries.reduce((sum, row) => sum + row.bytes, 0),
    shipped, references, originalReports: REQUIRED_REPORTS.map(file => byPath.get(file)), evidenceEntries: entries };
  fs.writeFileSync(path.join(portableRoot, 'DOCUMENTATION.json'), JSON.stringify(result, null, 2) + '\n');
  return { ...result, evidenceRoot };
}
