import nextEnv from "@next/env";
import fs from "node:fs";
import path from "node:path";

const projectDir = process.cwd();
const { loadEnvConfig } = nextEnv;

loadEnvConfig(projectDir, process.env.NODE_ENV !== "production");

const parseExtent = (value) => {
  if (!value) {
    return [13508849, 3608036, 13555781, 3633813];
  }

  const extent = value.split(",").map(Number);
  return extent.length === 4 && extent.every(Number.isFinite)
    ? extent
    : [13508849, 3608036, 13555781, 3633813];
};

const config = {
  BACKEND_URL: process.env.BACKEND_URL || "http://127.0.0.1:8000",
  AGENT_URL: process.env.AGENT_URL || "http://127.0.0.1:8788",
  MAP_URL: process.env.MAP_URL || "http://127.0.0.1:8080/geoserver",
  MAP_WORKSPACE: process.env.MAP_WORKSPACE || "tjwater",
  MAP_EXTENT: parseExtent(process.env.MAP_EXTENT),
  NETWORK_NAME: process.env.NETWORK_NAME || "tjwater",
  MAPBOX_TOKEN: process.env.MAPBOX_TOKEN || "",
  TIANDITU_TOKEN: process.env.TIANDITU_TOKEN || "",
};

const outputPath = path.join(projectDir, "public", "runtime-config.js");

fs.writeFileSync(
  outputPath,
  `window.__TJWATER_RUNTIME_CONFIG__ = ${JSON.stringify(config)};\n`,
);

console.log(`Generated ${path.relative(projectDir, outputPath)}`);
