import { existsSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { rootPath } from "./config";

export function canonicalComposeEnvFile(): string {
  const explicitFile = process.env.UNIDESK_COMPOSE_ENV_FILE?.trim();
  if (explicitFile) return explicitFile;
  const stateDir = process.env.UNIDESK_STATE_DIR?.trim();
  if (stateDir) return join(stateDir, "docker-compose.env");
  return rootPath(".state", "docker-compose.env");
}

function unquoteEnvValue(value: string): string {
  const trimmed = value.trim();
  if (trimmed.length < 2) return trimmed;
  const first = trimmed[0];
  const last = trimmed[trimmed.length - 1];
  if ((first !== "\"" && first !== "'") || last !== first) return trimmed;
  return trimmed.slice(1, -1);
}

export function readEnvFileValues(path: string): Map<string, string> {
  const values = new Map<string, string>();
  if (!existsSync(path)) return values;
  for (const line of readFileSync(path, "utf8").split(/\r?\n/u)) {
    if (line.trim().length === 0 || line.trimStart().startsWith("#")) continue;
    const index = line.indexOf("=");
    if (index <= 0) continue;
    const key = line.slice(0, index).trim();
    if (!/^[A-Za-z_][A-Za-z0-9_]*$/u.test(key)) continue;
    values.set(key, unquoteEnvValue(line.slice(index + 1)));
  }
  return values;
}

export function composeRuntimeEnvValue(key: string, env: NodeJS.ProcessEnv = process.env): string | null {
  const fromProcess = env[key]?.trim();
  if (fromProcess !== undefined && fromProcess.length > 0) return fromProcess;
  const fromFile = readEnvFileValues(canonicalComposeEnvFile()).get(key)?.trim();
  return fromFile === undefined || fromFile.length === 0 ? null : fromFile;
}
