import { watch } from "node:fs";
import { readdir, readFile, mkdir, writeFile } from "node:fs/promises";
import { fileURLToPath, pathToFileURL } from "node:url";
import { join } from "node:path";
import { spawnSync } from "node:child_process";
import {
  createOpenApi,
  createPlatforms,
} from "../disposabl-kit/server/lib/platform-spec";

import config from "../../disposabl.json";
import { pageRoutes } from "../disposabl-kit/client/lib/prerender";

const root = fileURLToPath(new URL(".", import.meta.url));
const convex = join(root, "convex");
const output = join(root, "generated");
const canonical = (value: unknown): string =>
  JSON.stringify(value, (_, item) =>
    item && typeof item === "object" && !Array.isArray(item)
      ? Object.fromEntries(
          Object.entries(item).sort(([a], [b]) => a.localeCompare(b)),
        )
      : item,
  );

async function writeChanged(path: string, text: string) {
  if ((await readFile(path, "utf8").catch(() => "")) !== text)
    await writeFile(path, text);
}

/** Discover opt-in modules, validate the contract, then update both transports together. */
export async function generate(acceptBreaking = false) {
  const files = await readdir(convex, { recursive: true });
  const modules: Record<string, Record<string, unknown>> = {};
  for (const file of files.sort()) {
    if (
      file.startsWith("_generated/") ||
      !file.endsWith(".ts") ||
      file.endsWith(".d.ts")
    )
      continue;
    const source = await readFile(join(convex, file), "utf8");
    if (!/\bplatforms\s*:\s*true\b/.test(source)) continue;
    if (/^[\s;]*["']use node["']/.test(source))
      throw new Error(
        `${file}: platform validators must be in a default-runtime module; delegate Node work through an internal action.`,
      );
    modules[file.slice(0, -3)] = await import(
      pathToFileURL(join(convex, file)).href
    );
  }
  const next = createOpenApi(createPlatforms(modules).spec);
  const previous = await readFile(join(output, "openapi.json"), "utf8")
    .then(JSON.parse)
    .catch((error) => {
      if (error.code !== "ENOENT") throw error;
      return null;
    });
  const changes = previous
    ? Object.keys(previous.paths).filter(
        (path) =>
          canonical(previous.paths[path]) !== canonical(next.paths[path]),
      )
    : [];
  if (changes.length && !acceptBreaking)
    throw new Error(
      `Contract changed or removed: ${changes.join(", ")}. Review the changes, then run bun run generate --accept-breaking to accept a major version.`,
    );
  if (previous) {
    const [major, minor, patch] = previous.info.version.split(".").map(Number);
    next.info.version = changes.length
      ? `${major + 1}.0.0`
      : canonical(previous.paths) !== canonical(next.paths)
        ? `${major}.${minor + 1}.0`
        : `${major}.${minor}.${patch}`;
  }
  const paths = Object.keys(modules);
  const registry =
    "// Generated by bun run generate. Do not edit.\n" +
    paths
      .map(
        (path, index) =>
          `import * as m${index} from ${JSON.stringify(`../convex/${path}`)};`,
      )
      .join("\n") +
    `\nexport default {${paths.map((path, index) => `${JSON.stringify(path)}: m${index}`).join(",")}};\n`;
  await mkdir(output, { recursive: true });
  await writeChanged(
    join(output, "pages.json"),
    JSON.stringify(
      pageRoutes(
        await readFile(
          join(root, "../../apps/web/src/routeTree.gen.ts"),
          "utf8",
        ),
      ),
      null,
      2,
    ) + "\n",
  );
  await writeChanged(
    join(output, "openapi.json"),
    JSON.stringify(next, null, 2) + "\n",
  );
  await writeChanged(join(output, "platforms.ts"), registry);
  const formatted = spawnSync(process.execPath, ["fmt", output], {
    stdio: "pipe",
  });
  if (formatted.status !== 0)
    throw new Error("Could not format generated contract");
  if (config.platforms.includes("typescript-sdk")) {
    const sdk = spawnSync(process.execPath, ["run", "generate"], {
      cwd: join(root, "../sdk"),
      stdio: "inherit",
    });
    if (sdk.status !== 0) throw new Error("SDK generation failed");
  }
  console.log(
    `Generated ${Object.keys(next.paths).length} operations, contract ${next.info.version}.`,
  );
}

if (import.meta.main) {
  if (process.argv.includes("--watch")) {
    const run = () =>
      spawnSync(process.execPath, [fileURLToPath(import.meta.url)], {
        stdio: "inherit",
      });
    run();
    let timer: ReturnType<typeof setTimeout>;
    watch(convex, { recursive: true }, (_, file) => {
      if (!file?.endsWith(".ts")) return;
      clearTimeout(timer);
      timer = setTimeout(run, 200);
    });
  } else await generate(process.argv.includes("--accept-breaking"));
}
