#!/usr/bin/env node

// Self-executing script to generate variables.json and variables.tsp from env/.env.{environment}
(async function main() {
  const fs = require("fs");
  const path = require("path");

  try {
    const envArg = process.argv[2] || "dev";

    // src/agent is the parent of this scripts directory
    const repoAgentDir = path.resolve(__dirname, "..");
    const envFilePath = path.join(repoAgentDir, "env", `.env.${envArg}`);
    const outTspPath = path.join(repoAgentDir, "src/agent/env.tsp");

    if (!fs.existsSync(envFilePath)) {
      console.error(`Environment file not found: ${envFilePath}`);
      console.error(`Usage: node generate-env.js <environment>  (e.g. dev, prod)`);
      process.exitCode = 2;
      return;
    }

    const raw = fs.readFileSync(envFilePath, "utf8");

    const vars = {};

    for (const rawLine of raw.split(/\r?\n/)) {
      const line = rawLine.trim();
      if (!line || line.startsWith("#")) continue;

      // support lines like KEY=value or export KEY=value
      const cleaned = line.replace(/^export\s+/, "");
      const match = cleaned.match(/^([A-Za-z0-9_.-]+)\s*=\s*(.*)$/);
      if (!match) continue;

      const key = match[1];
      let value = match[2] || "";

      // strip surrounding single or double quotes
      if (
        (value.startsWith('"') && value.endsWith('"')) ||
        (value.startsWith("'") && value.endsWith("'"))
      ) {
        value = value.slice(1, -1);
      }

      // Unescape common sequences (keep as-is if not needed)
      value = value.replace(/\\n/g, "\n").replace(/\\r/g, "\r");

      vars[key] = value;
    }

    const tspLines = [];
    tspLines.push("// Auto-generated by scripts/generate-env.js - DO NOT EDIT");
    tspLines.push(`// Source: env/.env.${envArg}`);
    tspLines.push("");
    tspLines.push("namespace Environment {");

    const keys = Object.keys(vars).sort();
    for (const originalKey of keys) {
      const value = vars[originalKey];

      // Convert original env key to a safe TypeSpec identifier: replace invalid chars with _ and ensure it doesn't start with a digit
      let ident = originalKey.replace(/[^A-Za-z0-9_]/g, "_");
      if (/^[0-9]/.test(ident)) ident = "_" + ident;

      // Add a comment with the original env key for traceability
      tspLines.push(`  // ${originalKey}`);

      // Escape backslashes and double quotes for safe TS string literal
      const escaped = value.replace(/\\/g, "\\\\").replace(/\"/g, '\\"');

      tspLines.push(`  const ${ident} = "${escaped}";`);
      tspLines.push("");
    }

    tspLines.push("}");

    fs.writeFileSync(outTspPath, tspLines.join("\n") + "\n", "utf8");

    console.log(`Generated: ${outTspPath}`);
  } catch (err) {
    console.error("Failed to generate environment variables:", err && err.stack ? err.stack : err);
    process.exitCode = 1;
  }
})();
