import { randomBytes } from "node:crypto";
import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";

const envPath = resolve(process.cwd(), ".env");
const envExists = existsSync(envPath);
const original = envExists ? readFileSync(envPath, "utf8") : "";
const lines = original ? original.split(/\r?\n/) : [];

const parsed = new Map();
for (const line of lines) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith("#")) continue;
    const match = trimmed.match(/^([A-Z0-9_]+)\s*=\s*(.*)$/);
    if (!match) continue;
    parsed.set(match[1], match[2]);
}

const required = [
    {
        key: "DATABASE_URL",
        value: '"file:./dev.db"',
    },
    {
        key: "SESSION_SECRET",
        value: `"${randomBytes(32).toString("hex")}"`,
    },
    {
        key: "INIT_SETUP_TOKEN",
        value: `"${randomBytes(24).toString("hex")}"`,
    },
    {
        key: "INIT_DEFAULT_PASSWORD",
        value: `"${randomBytes(9).toString("base64url")}"`,
    },
];

const added = [];
for (const item of required) {
    if (!parsed.has(item.key)) {
        lines.push(`${item.key}=${item.value}`);
        added.push(item.key);
    }
}

if (!envExists && lines.length === 0) {
    lines.push("# Generated by scripts/init-env.mjs");
}

const next = `${lines.filter((line, index, arr) => !(line === "" && index === arr.length - 1)).join("\n")}\n`;
writeFileSync(envPath, next, "utf8");

if (added.length === 0) {
    console.log("init-env: no missing keys, .env unchanged");
} else {
    console.log(`init-env: added ${added.join(", ")}`);
}
