#!/usr/bin/env node
/* global console */
// Generate test bootstrap to set Zotero prefs from .env for repeatable runs.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

// Normalize root path for Windows (avoid duplicated drive letter issue)
const __filename = fileURLToPath(import.meta.url);
const scriptDir = path.dirname(__filename);
const root = path.resolve(scriptDir, "..");
const envPath = path.join(root, ".env");
const outPath = path.join(root, "test", "00.env-setup.test.ts");

function parseEnv(text) {
  const env = {};
  for (const rawLine of text.split(/\r?\n/)) {
    const line = rawLine.trim();
    if (!line || line.startsWith("#")) continue;
    const idx = line.indexOf("=");
    if (idx === -1) continue;
    const k = line.slice(0, idx).trim();
    let v = line.slice(idx + 1).trim();
    if (
      (v.startsWith('"') && v.endsWith('"')) ||
      (v.startsWith("'") && v.endsWith("'"))
    ) {
      v = v.slice(1, -1);
    }
    env[k] = v;
  }
  return env;
}

let env = {};
if (fs.existsSync(envPath)) {
  env = parseEnv(fs.readFileSync(envPath, "utf8"));
}

const provider = env.AIBUTLER_PROVIDER || "google";
const stream = String(env.STREAM || "true").toLowerCase() === "true";
const temperature = env.TEMPERATURE || "0.7";
const topP = env.TOP_P || "1.0";
const maxTokens = env.MAX_TOKENS || "4096";
const requestTimeoutMs = env.REQUEST_TIMEOUT_MS || "15000";

// Map env -> prefs keys expected by LLMClient
const kv = [
  ["provider", provider],
  ["stream", stream],
  ["temperature", temperature],
  ["topP", topP],
  ["maxTokens", maxTokens],
  ["requestTimeout", requestTimeoutMs],
  // OpenAI
  ["openaiApiUrl", env.OPENAI_API_URL || ""],
  ["openaiApiKey", env.OPENAI_API_KEY || ""],
  ["openaiApiModel", env.OPENAI_MODEL || "gpt-3.5-turbo"],
  // Gemini
  ["geminiApiUrl", env.GEMINI_API_URL || ""],
  ["geminiApiKey", env.GEMINI_API_KEY || ""],
  ["geminiModel", env.GEMINI_MODEL || "gemini-2.5-pro"],
  // Anthropic
  ["anthropicApiUrl", env.ANTHROPIC_API_URL || ""],
  ["anthropicApiKey", env.ANTHROPIC_API_KEY || ""],
  ["anthropicModel", env.ANTHROPIC_MODEL || "claude-3-5-sonnet-20241022"],
];

const pkgJsonPath = path.join(root, "package.json");
let prefsPrefix = "extensions.zotero.aiButler";
try {
  const pkg = requireJSON(pkgJsonPath);
  prefsPrefix = pkg?.config?.prefsPrefix || prefsPrefix;
} catch {
  console.warn("[gen-env-setup] package.json not found, using fallback prefix");
}

const lines = [];
lines.push("// Auto-generated by scripts/gen-env-setup.mjs — DO NOT EDIT");
lines.push("// Preload environment-based preferences for tests");
lines.push("(() => {");
lines.push("  try {");
for (const [k, v] of kv) {
  const val = typeof v === "boolean" ? v : JSON.stringify(String(v));
  lines.push(`    // ${k}`);
  lines.push(
    `    Zotero?.Prefs?.set?.(${JSON.stringify(prefsPrefix + "." + k)}, ${val}, true);`,
  );
}
lines.push("  } catch (e) { /* ignore in non-test env */ }");
lines.push("})();");
lines.push("export {};\n");

// ensure test dir exists
fs.mkdirSync(path.dirname(outPath), { recursive: true });
fs.writeFileSync(outPath, lines.join("\n"), "utf8");

console.log("[gen-env-setup] wrote", outPath);

function requireJSON(p) {
  return JSON.parse(fs.readFileSync(p, "utf8"));
}
