import { readFileSync } from "node:fs";
import { join } from "node:path";
import { configDir } from "../paths";

const DEFAULT_KANBOARD_BASE_URL = "http://127.0.0.1:31339/jsonrpc.php";

export interface IncidentsConnection {
  baseUrl: string;
  token: string;
}

export function kanboardEnvFile(): string {
  return join(configDir(), "kanboard.env");
}

function stripQuotes(value: string): string {
  if (value.length >= 2 && value[0] === value.at(-1) && (value[0] === "\"" || value[0] === "'")) {
    return value.slice(1, -1);
  }
  return value;
}

function stripInlineComment(raw: string): string {
  let quote: "'" | '"' | null = null;
  for (let index = 0; index < raw.length; index += 1) {
    const char = raw[index];

    if (quote === null && char === "#") {
      return raw.slice(0, index).trim();
    }

    if (char === quote) {
      quote = null;
      continue;
    }

    if (quote === null && (char === "\"" || char === "'")) {
      quote = char;
    }
  }

  return raw.trim();
}

function parseEnvFile(text: string): Record<string, string> {
  const entries = Object.create(null) as Record<string, string>;
  for (const rawLine of text.split(/\r?\n/)) {
    const trimmed = rawLine.trim();
    if (!trimmed || trimmed.startsWith("#")) {
      continue;
    }

    const stripped = stripInlineComment(trimmed);
    if (!stripped) {
      continue;
    }

    const equals = stripped.indexOf("=");
    if (equals < 0) {
      continue;
    }

    const key = stripped.slice(0, equals).trim();
    const value = stripQuotes(stripped.slice(equals + 1).trim());
    if (!key) {
      continue;
    }
    entries[key] = value;
  }
  return entries;
}

export function loadIncidentsConnection(): IncidentsConnection | null {
  let content: string;
  try {
    content = readFileSync(kanboardEnvFile(), "utf8");
  } catch {
    return null;
  }

  const parsed = parseEnvFile(content);
  const token = parsed.KANBOARD_API_TOKEN?.trim();
  if (!token) {
    return null;
  }

  const baseUrl = process.env.OVERDECK_KANBOARD_URL?.trim() || DEFAULT_KANBOARD_BASE_URL;
  return { baseUrl, token };
}
