/* Omni checking that a thing works, not that its file exists (docs/specs/omni-agent-todo.md, section 2).
   `voiceProviders` and the setup steps only look for a key or a login; these ask:

   - test_voice_key   one free, authenticated call to the provider (Fish: the wallet; Cartesia: the voice list;
                      ElevenLabs: the user): 200 is a key that works, 401/403 a refused one, 429 a plan limit.
                      The key is read here and never returned, logged or put in a message.
   - check_claude     `claude auth status` for each enabled account of this computer: logged in, and on which plan.
                      It starts no session, so it spends nothing.
   - check_render     one still of the base scene through tools/render.mjs with the downloaded Chrome and ffmpeg:
                      the same path every video's render takes.

   An answer is kept for a few minutes (a repeated ask costs nothing and does not call the provider again);
   `fresh` skips it. */

import { mkdtempSync, rmSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { accountsOf, binOf, envFor, loginOf } from "../../../tools/lib/agents.mjs";
import { depsEnv } from "../../../tools/lib/deps.mjs";
import { spawn } from "../lib/runtime";
import { CODE_ROOT, NODE, TOOLS_DIR } from "./root";
import { providerKey, readConfig } from "./settings";

type Out = Record<string, unknown>;

export const VOICE_PROVIDERS = ["fish", "cartesia", "elevenlabs"] as const;
export type VoiceProvider = (typeof VOICE_PROVIDERS)[number];
const NAMES: Record<VoiceProvider, string> = { fish: "Fish Audio", cartesia: "Cartesia", elevenlabs: "ElevenLabs" };

const TTL_MS = 10 * 60_000;
const kept = new Map<string, { at: number; value: Out }>();
const keep = (id: string, value: Out) => {
  kept.set(id, { at: Date.now(), value });
  return value;
};
const recall = (id: string, fresh: boolean) => {
  const k = kept.get(id);
  return !fresh && k && Date.now() - k.at < TTL_MS ? { ...k.value, cached: true } : null;
};
/* tests and a changed key start over */
export const forgetVerification = () => kept.clear();

/* --- a voice provider's key --------------------------------------------------------------------------- */
function probe(provider: VoiceProvider, key: string): { url: string; headers: Record<string, string> } {
  if (provider === "fish")
    return { url: "https://api.fish.audio/wallet/self/api-credit", headers: { Authorization: `Bearer ${key}` } };
  if (provider === "cartesia")
    return {
      url: "https://api.cartesia.ai/voices?limit=1",
      headers: {
        Authorization: `Bearer ${key}`,
        "Cartesia-Version": String(readConfig()?.voice?.cartesia?.api_version ?? "2026-08-14"),
      },
    };
  return { url: "https://api.elevenlabs.io/v1/user", headers: { "xi-api-key": key } };
}

export async function testVoiceKey(
  provider: VoiceProvider,
  fresh = false,
  fetcher: typeof fetch = fetch,
): Promise<Out> {
  const name = NAMES[provider];
  const key = providerKey(provider);
  if (!key)
    return {
      ok: false,
      provider: name,
      problem: "no_key",
      message: `Não há chave da ${name} neste computador: Configurações, aba Provedores, é onde ela é colada.`,
    };
  /* the answer is kept per key, so pasting another one asks again */
  const id = `voice:${provider}:${key.slice(-6)}`;
  const hit = recall(id, fresh);
  if (hit) return hit;
  const { url, headers } = probe(provider, key);
  try {
    const r = await fetcher(url, { headers, signal: AbortSignal.timeout(10_000) });
    if (r.ok) return keep(id, { ok: true, provider: name, message: `A chave da ${name} funciona.` });
    if (r.status === 401 || r.status === 403)
      return keep(id, {
        ok: false,
        provider: name,
        problem: "refused",
        status: r.status,
        message: `A ${name} recusou a chave (${r.status}): ela está errada, vencida ou sem permissão. Copie de novo, sem espaço nem aspas.`,
      });
    if (r.status === 429)
      return keep(id, {
        ok: false,
        provider: name,
        problem: "limit",
        status: 429,
        message: `A chave da ${name} é válida, mas o plano chegou ao limite de uso (429).`,
      });
    return {
      ok: false,
      provider: name,
      problem: "unexpected",
      status: r.status,
      message: `A ${name} respondeu ${r.status}: não deu para confirmar a chave agora.`,
    };
  } catch {
    /* not kept: a network failure says nothing about the key */
    return {
      ok: false,
      provider: name,
      problem: "network",
      message: `Não consegui falar com a ${name} agora: a internet, uma VPN ou um proxy pode estar bloqueando.`,
    };
  }
}

/* --- the Claude Code account -------------------------------------------------------------------------- */
type Run = { code: number; stdout: string; stderr: string; timedOut: boolean };

/* one command with a deadline: output kept to what a message can hold */
export async function runTimed(cmd: string[], env: Record<string, string | undefined>, ms: number): Promise<Run> {
  const p = spawn(cmd, {
    cwd: CODE_ROOT,
    stdin: "ignore",
    stdout: "pipe",
    stderr: "pipe",
    env: { ...process.env, ...env },
  });
  let timedOut = false;
  const timer = setTimeout(() => {
    timedOut = true;
    p.kill();
  }, ms);
  const [stdout, stderr, code] = await Promise.all([
    new Response(p.stdout as ReadableStream<Uint8Array>).text(),
    new Response(p.stderr as ReadableStream<Uint8Array>).text(),
    p.exited,
  ]);
  clearTimeout(timer);
  return { code, stdout: stdout.slice(-4000), stderr: stderr.slice(-4000), timedOut };
}

type Account = { id: string; dir: string; provider: string; enabled: boolean };

export async function checkClaude(
  fresh = false,
  run: typeof runTimed = runTimed,
  accounts: Account[] = accountsOf(readConfig()),
): Promise<Out> {
  const on = accounts.filter(a => a.enabled && a.provider === "claude");
  if (!on.length)
    return {
      ok: false,
      problem: "no_account",
      message: "Nenhuma conta do Claude Code está ligada neste computador: Configurações, aba Omni, para ligar uma.",
    };
  const id = `claude:${on.map(a => a.id).join(",")}`;
  const hit = recall(id, fresh);
  if (hit) return hit;
  const cfg = readConfig();
  const found: Out[] = [];
  for (const a of on) {
    const r = await run([binOf(a, cfg), "auth", "status"], envFor(a), 20_000);
    let status: { loggedIn?: boolean; subscriptionType?: string; email?: string } = {};
    try {
      status = JSON.parse(r.stdout);
    } catch {
      /* not JSON: an old Claude Code, or it failed */
    }
    /* an old Claude Code has no `auth status`: the login file is the answer */
    const logged = status.loggedIn ?? !!loginOf(a);
    found.push({
      account: a.id,
      logged_in: !!logged,
      email: status.email ?? loginOf(a)?.email ?? null,
      plan: status.subscriptionType ?? null,
      ...(r.timedOut ? { timed_out: true } : {}),
    });
  }
  const any = found.some(f => f.logged_in);
  /* the free plan isn't among the plans Anthropic lists for Claude Code (Pro, Max): the login works, the sessions may not */
  const onlyFree = any && found.filter(f => f.logged_in).every(f => f.plan === "free");
  const out: Out = any
    ? {
        ok: !onlyFree,
        accounts: found,
        ...(onlyFree
          ? {
              problem: "free_plan",
              message:
                "A conta entrou, mas é do plano gratuito, que não está entre os que a Anthropic lista para o Claude Code (Pro e Max): as sessões podem não rodar.",
            }
          : { message: "O Claude Code está conectado." }),
      }
    : {
        ok: false,
        accounts: found,
        problem: "not_logged_in",
        message: "Nenhuma conta do Claude Code está com login neste computador: connect_claude abre o login.",
      };
  /* a missing login is not kept: the user is about to fix it */
  return any ? keep(id, out) : out;
}

/* --- the render --------------------------------------------------------------------------------------- */
export async function checkRender(fresh = false, run: typeof runTimed = runTimed): Promise<Out> {
  const hit = recall("render", fresh);
  if (hit) return hit;
  const dir = mkdtempSync(join(tmpdir(), "omni-render-check-"));
  const png = join(dir, "still.png");
  const t0 = Date.now();
  try {
    const r = await run(
      [NODE, join(TOOLS_DIR, "render.mjs"), join(CODE_ROOT, "templates", "scene.html"), "--still", png, "--at", "0"],
      depsEnv(),
      60_000,
    );
    let bytes = 0;
    try {
      bytes = statSync(png).size;
    } catch {
      /* no file */
    }
    if (r.code === 0 && bytes > 2000)
      return keep("render", {
        ok: true,
        ms: Date.now() - t0,
        message: "O render funciona: o Chrome sem janela desenhou um quadro de teste.",
      });
    const last = (r.stderr || r.stdout).trim().split("\n").slice(-3).join(" ").slice(0, 300);
    return {
      ok: false,
      problem: r.timedOut ? "timeout" : "failed",
      message: r.timedOut
        ? "O render passou de 60 s sem terminar: o Chrome sem janela pode ainda estar sendo baixado."
        : "O render não funcionou: o Chrome sem janela ou o ffmpeg não responderam.",
      detail: last,
    };
  } finally {
    rmSync(dir, { recursive: true, force: true });
  }
}
