import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { dirname, join } from "node:path";
import type { InstallContext, InstallResult } from "./types.ts";
import { secureAtomicWriteSync } from "./blocks/secureWrite.ts";

const ENV_KEY = "ANTHROPIC_API_BASE";

export function installAider(ctx: InstallContext): InstallResult {
  const path = join(ctx.home, ".aider.conf.yml");
  mkdirSync(dirname(path), { recursive: true });
  const url = `http://127.0.0.1:${ctx.port}`;
  const newEntry = `${ENV_KEY}=${url}`;

  let lines: string[] = [];
  if (existsSync(path)) {
    lines = readFileSync(path, "utf8").split("\n");
  }

  // Find set-env block. Format: `set-env:` followed by `  - KEY=VAL` lines.
  const out: string[] = [];
  let i = 0;
  let foundSetEnv = false;
  let replaced = false;
  while (i < lines.length) {
    const line = lines[i]!;
    if (/^set-env:\s*$/.test(line)) {
      foundSetEnv = true;
      out.push(line);
      i++;
      // collect existing - items
      while (i < lines.length && /^\s+-\s+/.test(lines[i]!)) {
        const item = lines[i]!.replace(/^\s+-\s+/, "").trim();
        if (item.startsWith(`${ENV_KEY}=`)) {
          out.push(`  - ${newEntry}`);
          replaced = true;
        } else {
          out.push(lines[i]!);
        }
        i++;
      }
      if (!replaced) out.push(`  - ${newEntry}`);
      continue;
    }
    out.push(line);
    i++;
  }
  if (!foundSetEnv) {
    if (out.length > 0 && out[out.length - 1] !== "") out.push("");
    out.push("set-env:");
    out.push(`  - ${newEntry}`);
  }
  secureAtomicWriteSync(path, out.join("\n"));
  return { ok: true, path, message: `aider → ${url}` };
}
