const { execSync } = require("node:child_process");
const { existsSync } = require("node:fs");
const path = require("node:path");
const dotenv = require("dotenv");

dotenv.config({ path: ".env" });
dotenv.config({ path: ".env.local", override: true });

const apiBaseUrl =
  process.env.API_BASE_URL ||
  process.env.NEXT_PUBLIC_API_BASE_URL ||
  "http://localhost:8081";

const openApiUrl =
  process.env.OPENAPI_URL ||
  process.env.REACT_APP_OPENAPI_URL ||
  `${apiBaseUrl.replace(/\/$/, "")}/brapi/v2/openapi.json`;

process.env.API_BASE_URL = apiBaseUrl;
if (!process.env.OPENAPI_URL && !process.env.REACT_APP_OPENAPI_URL) {
  process.env.OPENAPI_URL = openApiUrl;
}

console.log("API_BASE_URL:", apiBaseUrl);
console.log("OPENAPI_URL:", openApiUrl);
console.log("开始生成 OpenAPI 客户端...");

execSync("npx @hey-api/openapi-ts", {
  stdio: "inherit",
  env: process.env
});

const apiDir = path.resolve(process.cwd(), "src/lib/api");
const required = ["types.gen.ts", "sdk.gen.ts", "index.ts", "client.gen.ts"];
const missing = required.filter((file) => !existsSync(path.join(apiDir, file)));

if (missing.length > 0) {
  console.error("生成失败，缺失文件:", missing.join(", "));
  process.exit(1);
}

console.log("OpenAPI 客户端生成完成：src/lib/api");
