/**
 * Emit the typed-edge enumeration into the public docs from the
 * `TYPED_EDGE_ALLOWLIST` source of truth, so the prompt, the validator,
 * and the docs cannot drift from each other.
 *
 * Targets:
 *   - .docs/neo4j.md (parent maxy-code .docs surface)
 *   - platform/plugins/docs/references/neo4j.md (bundled into the payload)
 *
 * Replaces the block delimited by:
 *   <!-- TYPED-EDGE-TABLE:START -->
 *   <!-- TYPED-EDGE-TABLE:END -->
 *
 * Usage:
 *   node --loader ts-node/esm scripts/generate-edge-docs.ts
 */

import { writeFileSync, readFileSync, existsSync } from "node:fs";
import { resolve } from "node:path";
import { TYPED_EDGE_ALLOWLIST } from "../src/lib/typed-edge-schema.js";

const TARGET_PATHS = [
  // maxy-code/.docs/neo4j.md — resolved relative to this script.
  resolve(import.meta.dirname ?? __dirname, "../../../../../.docs/neo4j.md"),
  // bundled docs twin
  resolve(import.meta.dirname ?? __dirname, "../../../docs/references/neo4j.md"),
];

const START_MARKER = "<!-- TYPED-EDGE-TABLE:START -->";
const END_MARKER = "<!-- TYPED-EDGE-TABLE:END -->";

function buildTable(): string {
  const rows = TYPED_EDGE_ALLOWLIST
    .map(({ sourceLabel, edgeType, targetLabel }) => `| ${sourceLabel} | ${edgeType} | ${targetLabel} |`)
    .join("\n");
  return [
    START_MARKER,
    "",
    "<!-- Generated by platform/plugins/memory/mcp/scripts/generate-edge-docs.ts from TYPED_EDGE_ALLOWLIST. Do not edit by hand. -->",
    "",
    "| Source label | Edge type | Target label |",
    "|---|---|---|",
    rows,
    "",
    END_MARKER,
  ].join("\n");
}

function applyToFile(path: string, table: string): "wrote" | "missing" | "no-markers" {
  if (!existsSync(path)) return "missing";
  const current = readFileSync(path, "utf-8");
  const startIdx = current.indexOf(START_MARKER);
  const endIdx = current.indexOf(END_MARKER);
  let next: string;
  if (startIdx === -1 || endIdx === -1) {
    // No markers — append the section under a clear heading rather than
    // failing. Idempotent on subsequent runs because we add the markers.
    next = `${current.trimEnd()}\n\n## Typed-edge allowlist (generated)\n\n${table}\n`;
    writeFileSync(path, next);
    return "wrote";
  }
  next = current.slice(0, startIdx) + table + current.slice(endIdx + END_MARKER.length);
  writeFileSync(path, next);
  return "wrote";
}

function main(): void {
  const table = buildTable();
  for (const path of TARGET_PATHS) {
    const result = applyToFile(path, table);
    console.log(`[generate-edge-docs] ${path} -> ${result}`);
  }
}

main();
