import path from "node:path";
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";

export type BotConfig = {
  panelUrl: string;
  workerId: string;
  workerSecret: string;
  oauthMasterKey: string;
  vaultPath: string;
  kickClientId: string;
  kickClientSecret: string;
  kickRedirectUri: string;
  kickScopes: string[];
  pollIntervalMs: number;
  heartbeatIntervalMs: number;
  botUsername: "fiIyx";
  botKickUserId: string;
  roleCheckUrlTemplate: string;
  legacyRoot: string;
};

const here = path.dirname(fileURLToPath(import.meta.url));
const appRoot = path.resolve(here, "..");
const projectRoot = path.resolve(appRoot, "..", "..");

const loadEnvFile = (file: string): void => {
  try {
    for (const line of readFileSync(file, "utf8").split(/\r?\n/)) {
      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith("#") || !trimmed.includes("=")) continue;
      const index = trimmed.indexOf("=");
      const name = trimmed.slice(0, index).trim();
      let value = trimmed.slice(index + 1).trim();
      if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) {
        value = value.slice(1, -1);
      }
      if (name && process.env[name] === undefined) process.env[name] = value;
    }
  } catch {
  }
};
loadEnvFile(path.join(projectRoot, ".env"));

const required = (name: string): string => {
  const value = process.env[name]?.trim() ?? "";
  if (!value) throw new Error(`Variable requise absente : ${name}`);
  return value;
};

export const loadConfig = (): BotConfig => ({
  panelUrl: required("FILYX_PANEL_URL").replace(/\/+$/, ""),
  workerId: required("FILYX_WORKER_ID"),
  workerSecret: required("FILYX_WORKER_SECRET"),
  oauthMasterKey: process.env.FILYX_OAUTH_MASTER_KEY?.trim() || required("FILYX_COOKIE_MASTER_KEY"),
  vaultPath: process.env.FILYX_OAUTH_VAULT?.trim() || path.join(appRoot, "runtime", "secure", "fiIyx-oauth.enc"),
  kickClientId: required("FILYX_KICK_CLIENT_ID"),
  kickClientSecret: required("FILYX_KICK_CLIENT_SECRET"),
  kickRedirectUri: process.env.FILYX_KICK_REDIRECT_URI?.trim() || "http://localhost:47831/oauth/callback",
  kickScopes: (process.env.FILYX_KICK_SCOPES?.trim() || "user:read chat:write moderation:ban moderation:chat_message:manage")
    .split(/\s+/)
    .filter(Boolean),
  pollIntervalMs: Math.max(700, Number(process.env.FILYX_POLL_INTERVAL_MS) || 1_500),
  heartbeatIntervalMs: Math.max(5_000, Number(process.env.FILYX_HEARTBEAT_INTERVAL_MS) || 15_000),
  botUsername: "fiIyx",
  botKickUserId: process.env.FILYX_BOT_KICK_ID?.trim() || "",
  roleCheckUrlTemplate: process.env.FILYX_KICK_ROLE_CHECK_URL_TEMPLATE?.trim() || "",
  legacyRoot: process.env.FILYX_LEGACY_ROOT?.trim() || path.resolve(appRoot, "..", "..", "legacy")
});
