import { readFileSync, writeFileSync } from "node:fs";
import { registry } from "./routes";
import type { Registry, RouteRegistryEntry } from "./schema";

/**
 * Generate .well-known/x402.json + OpenAPI + endpoint count from `registry`.
 * Run once per CI, output goes to pr7/generated.
 */

function generateWellKnown(reg: Registry) {
  return {
    x402Version: 2,
    generatedAt: reg.generatedAt,
    protocol: "vaultfire",
    protocolVersions: ["v2", "v3"],
    endpoints: reg.routes
      .filter((r) => !r.free)
      .map((r) => ({
        id: r.id,
        method: r.method,
        path: r.path,
        version: r.version,
        contractStatus: r.contractStatus,
        price: r.price!.amount,
        asset: r.price!.asset,
        network: r.price!.network,
        payee: r.price!.payee,
        x402Version: r.price!.x402Version,
        finality: r.finality,
      })),
  };
}

function generateOpenApi(reg: Registry) {
  return {
    openapi: "3.1.0",
    info: {
      title: "Vaultfire API",
      version: reg.version,
      description: "V2 (legacy, preserved) + V3 (audited pilot) routes. Generated from the typed route registry — never hand-edit.",
    },
    paths: Object.fromEntries(
      reg.routes.map((r: RouteRegistryEntry) => [
        r.path,
        {
          [r.method.toLowerCase()]: {
            operationId: r.id,
            summary: r.description,
            "x-protocol-version": r.version,
            "x-contract-status": r.contractStatus,
            "x-finality": r.finality,
            "x-data-source": r.dataSource,
            "x-privacy": r.privacy,
            "x-idempotency": r.idempotencyRule,
            "x-price": r.free ? undefined : r.price,
            requestBody: r.method === "GET" ? undefined : { content: { "application/json": { schema: { $ref: r.requestSchema } } } },
            responses: {
              "200": { description: "ok", content: { "application/json": { schema: { $ref: r.responseSchema } } } },
              "402": { description: "Payment Required (x402)" },
              "503": { description: "Data source unavailable" },
            },
          },
        },
      ]),
    ),
  };
}

function countByVersion(reg: Registry) {
  const counts: Record<string, number> = {};
  for (const r of reg.routes) counts[r.version] = (counts[r.version] ?? 0) + 1;
  return counts;
}

if (require.main === module) {
  const wellKnown = generateWellKnown(registry);
  const openapi   = generateOpenApi(registry);
  const counts    = countByVersion(registry);
  writeFileSync("pr7/generated/well-known-x402.json", JSON.stringify(wellKnown, null, 2));
  writeFileSync("pr7/generated/openapi.json",         JSON.stringify(openapi, null, 2));
  writeFileSync("pr7/generated/endpoint-counts.json", JSON.stringify(counts, null, 2));
  process.stdout.write(`generated ${registry.routes.length} routes\n`);
}
