import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";

export interface V1Endpoint { key: string; file: string; line: number }
const SRC = join(import.meta.dirname, "../../../../backend/src");

/** Reads every endpoint out of the V1 source, so the list cannot drift or be forgotten. */
export function scanV1(): { endpoints: V1Endpoint[]; unparsed: string[] } {
  const index = readFileSync(join(SRC, "index.ts"), "utf8");
  const imports = new Map([...index.matchAll(/import\s+(?:\{\s*)?(\w+)(?:\s*\})?\s+from\s+"\.\/routes\/(\w+)\.js"/g)].map((m) => [m[1]!, m[2]!]));
  const mounts = new Map<string, string[]>();
  for (const m of index.matchAll(/app\.use\(\s*"([^"]+)"\s*,\s*(?:\w+\s*,\s*)*(\w+)\s*\)/g)) {
    const file = imports.get(m[2]!);
    if (file) mounts.set(file, [...(mounts.get(file) ?? []), m[1]!]);
  }
  const endpoints: V1Endpoint[] = [];
  const unparsed: string[] = [];
  for (const m of index.matchAll(/\bapp\.(get|post|put|patch|delete)\(\s*"([^"]+)"/g)) endpoints.push({ key: `${m[1]!.toUpperCase()} ${m[2]!}`, file: "index.ts", line: index.slice(0, m.index).split("\n").length });
  for (const name of readdirSync(join(SRC, "routes")).filter((f) => f.endsWith(".ts"))) {
    const text = readFileSync(join(SRC, "routes", name), "utf8");
    const bases = mounts.get(name.replace(/\.ts$/, ""));
    if (!bases) unparsed.push(`${name}: no mount found in index.ts`);
    for (const m of text.matchAll(/\b(\w*[rR]outer|r)\s*\.\s*(get|post|put|patch|delete)\(\s*([^,]+?)\s*,/g)) {
      const line = text.slice(0, m.index).split("\n").length;
      const paths = [...m[3]!.matchAll(/["'`]([^"'`]+)["'`]/g)].map((p) => p[1]!);
      if (!paths.length) { unparsed.push(`${name}:${line} ${m[3]!.slice(0, 60)}`); continue; }
      for (const base of bases ?? []) for (const path of paths) endpoints.push({ key: `${m[2]!.toUpperCase()} ${`${base}${path}`.replace(/\/$/, "").replaceAll("\\\\", "\\")}`, file: name, line });
    }
  }
  return { endpoints, unparsed };
}
