#!/usr/bin/env node
/**
 * Generiert TypeScript-Typen aus der RustyCMS OpenAPI-Spec.
 * Verwendet PUBLIC_CMS_URL aus .env (Default: http://localhost:3000).
 * RustyCMS muss laufen: cd ../rustycms && cargo run
 */
import { execSync } from "node:child_process";
import { readFileSync, existsSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";

const __dirname = dirname(fileURLToPath(import.meta.url));
const root = join(__dirname, "..");
const envPath = join(root, ".env");

if (existsSync(envPath)) {
  const lines = readFileSync(envPath, "utf8").split("\n");
  for (const line of lines) {
    const trimmed = line.trim();
    if (trimmed && !trimmed.startsWith("#") && trimmed.includes("=")) {
      const idx = trimmed.indexOf("=");
      const key = trimmed.slice(0, idx).trim();
      const value = trimmed.slice(idx + 1).trim().replace(/^["']|["']$/g, "");
      if (key && !process.env[key]) process.env[key] = value;
    }
  }
}

const base = (process.env.PUBLIC_CMS_URL || "http://localhost:3000").replace(/\/$/, "");
const specUrl = `${base}/api-docs/openapi.json`;
const outFile = join(root, "src/lib/cms-api.generated.ts");

console.log("Fetching OpenAPI spec from", specUrl);
console.log("Writing types to", outFile);

try {
  execSync(`npx openapi-typescript "${specUrl}" -o "${outFile}"`, {
    stdio: "inherit",
    cwd: root,
  });
  console.log("Done. Types are in src/lib/cms-api.generated.ts");
} catch (err) {
  console.error("\nFehler: OpenAPI-Spec konnte nicht geladen werden.");
  console.error("Ist RustyCMS gestartet? z.B.: cd ../rustycms && cargo run");
  process.exit(1);
}
