import { execFileSync } from "node:child_process";
import { mkdirSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";

const repoRoot = resolve(import.meta.dirname, "../../..");
const webRoot = resolve(import.meta.dirname, "..");
const outDir = resolve(webRoot, "lib/api");
const jsonPath = resolve(outDir, "openapi.json");
const dtsPath = resolve(outDir, "schema.d.ts");

mkdirSync(outDir, { recursive: true });

// 1) 后端 OpenAPI（uv 运行，离线，CI 无需起服务）
const uv = process.env.UV_BIN ?? "uv";
const spec = execFileSync(uv, ["run", "python", "-m", "ww_api.export_openapi"], {
  cwd: repoRoot,
  encoding: "utf8",
  maxBuffer: 32 * 1024 * 1024,
});
writeFileSync(jsonPath, spec);

// 2) OpenAPI → TS 类型（本地 bin，避免 pnpm exec 的工作区检查）
const bin = resolve(webRoot, "node_modules/.bin/openapi-typescript");
execFileSync(bin, [jsonPath, "-o", dtsPath], { cwd: webRoot, stdio: "inherit" });

console.log("gen:api done ->", dtsPath);
