/* Settings editable from the /settings screen. They live in two places:
   - omnivideo.config.json: voice_id, Fish model, price, Claude models, the agent accounts
     (agents: N Claude dirs and N Codex homes, never ~/.claude);
   - .env (outside git): the API keys. A key never goes back whole to the
     UI, only masked.
   tools/voice.py rereads both on every `voice`; the studio rereads the config on every session. */

import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, writeFileSync } from "node:fs";
import { createHash } from "node:crypto";
import { homedir } from "node:os";
import { join, resolve } from "node:path";
import { AVATAR_SEED } from "../../shared/schemas/agent";
import { ROOT, PYTHON, TOOLS_DIR, readJson, readText, run } from "./root";
import { forgetUsage } from "./usage";
import { forgetAccounts } from "./publish";
import { MODELS, EFFORTS, validate, inSkill, applyModels } from "../../../tools/models.mjs";
import {
  accountsOf,
  claudeBin,
  cleanAccounts,
  clearLimit,
  codexBin,
  codexModels,
  codexSettings,
  envFor,
  expandHome,
  limitedUntil,
  loginCommand,
  loginOf,
  pickAccount,
  tildify,
} from "../../../tools/lib/agents.mjs";

type Resp = { ok: true; output: string } | { ok: false; error: string };

const CONFIG_FILE = join(ROOT, "omnivideo.config.json");
const ENV_FILE = join(ROOT, ".env");

/* like the file is written by hand: short lists and objects on a single line */
const json = (v: unknown) =>
  JSON.stringify(v, null, 2)
    .replace(/\[\n\s+([^[\]{}]*?)\n\s*\]/g, (all, items: string) => {
      const line = `[${items.split(/,\n\s+/).join(", ")}]`;
      return line.length <= 72 ? line : all;
    })
    .replace(/\{\n\s+([^[\]{}]*?)\n\s*\}/g, (all, items: string) => {
      const line = `{ ${items.split(/,\n\s+/).join(", ")} }`;
      return line.length <= 90 ? line : all;
    });

export const readConfig = () => readJson<any>(CONFIG_FILE);

export function writeConfig(cfg: unknown) {
  const tmp = `${CONFIG_FILE}.${process.pid}.tmp`;
  writeFileSync(tmp, json(cfg) + "\n");
  renameSync(tmp, CONFIG_FILE);
  forgetUsage();
}

/* replaces (or adds) a key in the object without changing the order of the others */
function withKey(obj: Record<string, unknown>, k: string, v: unknown, after?: string) {
  if (k in obj || !after || !(after in obj)) return { ...obj, [k]: v };
  const next: Record<string, unknown> = {};
  for (const [kk, vv] of Object.entries(obj)) {
    next[kk] = vv;
    if (kk === after) next[k] = v;
  }
  return next;
}

/* --- .env ------------------------------------------------------------------------ */
const PUBLISH_ENV_KEYS = ["YOUTUBE_CLIENT_ID", "YOUTUBE_CLIENT_SECRET", "TIKTOK_CLIENT_KEY", "TIKTOK_CLIENT_SECRET"];
export const ENV_KEYS = [
  "FISH_API_KEY",
  "CARTESIA_API_KEY",
  "CARTESIA_ADMIN_API_KEY",
  "ELEVENLABS_API_KEY",
  ...PUBLISH_ENV_KEYS,
];

export function readEnv(): Record<string, string> {
  const vals: Record<string, string> = {};
  for (const line of (readText(ENV_FILE) ?? "").split("\n")) {
    const l = line.trim();
    if (!l || l.startsWith("#") || !l.includes("=")) continue;
    const i = l.indexOf("=");
    vals[l.slice(0, i).trim()] = l
      .slice(i + 1)
      .trim()
      .replace(/^["']|["']$/g, "");
  }
  return vals;
}

const mask = (v: string) => (v.length <= 12 ? "•".repeat(v.length) : `${v.slice(0, 7)}…${v.slice(-4)}`);

/* voice.py uses the environment variable before the .env one: flag when it hides the file */
function keyStatus(name: string, env: Record<string, string>) {
  const fromFile = env[name] || "";
  const fromEnv = process.env[name] || "";
  return {
    name,
    masked: fromFile ? mask(fromFile) : null,
    in_env: !!fromEnv && fromEnv !== fromFile,
  };
}

export function saveKey(name: unknown, value: unknown): Resp {
  if (typeof name !== "string" || !ENV_KEYS.includes(name)) return { ok: false, error: `chave desconhecida: ${name}` };
  const v = typeof value === "string" ? value.trim() : "";
  if (/[\s"'#]/.test(v)) return { ok: false, error: "a chave não pode ter espaço, aspas nem #" };
  const lines = (readText(ENV_FILE) ?? "").split("\n");
  const i = lines.findIndex(l => new RegExp(`^\\s*${name}\\s*=`).test(l));
  if (i >= 0) lines[i] = `${name}=${v}`;
  else {
    while (lines.length && lines.at(-1) === "") lines.pop();
    lines.push(`${name}=${v}`, "");
  }
  const tmp = `${ENV_FILE}.${process.pid}.tmp`;
  writeFileSync(tmp, lines.join("\n"), { mode: 0o600 });
  renameSync(tmp, ENV_FILE);
  forgetUsage();
  const isPublish = PUBLISH_ENV_KEYS.includes(name);
  if (isPublish) forgetAccounts();
  return { ok: true, output: v ? `gravada: vale para a próxima ${isPublish ? "conexão" : "voz"}` : "apagada" };
}

/* --- voice --------------------------------------------------------------------------- */
export const FISH_MODELS = ["s2.1-pro-free", "s2.1-pro"];

/* the free one (`s2.1-pro-free`, no cost) or the paid one (`s2.1-pro`, charged to the API balance).
   The fallback is tried when the first fails; null = no fallback. */
export function setFishModel(model: unknown, fallback: unknown): Resp {
  if (typeof model !== "string" || !FISH_MODELS.includes(model))
    return { ok: false, error: `modelo desconhecido: ${model}` };
  if (fallback !== null && (typeof fallback !== "string" || !FISH_MODELS.includes(fallback) || fallback === model))
    return { ok: false, error: `fallback inválido: ${fallback}` };
  const cfg = readConfig();
  if (!cfg?.voice?.fish) return { ok: false, error: "omnivideo.config.json sem voice.fish" };
  /* same key order, the fallback right after the model */
  const fish: Record<string, unknown> = {};
  for (const [k, v] of Object.entries(cfg.voice.fish)) {
    if (k === "fallback_model") continue;
    fish[k] = k === "model" ? model : v;
    if (k === "model" && fallback) fish.fallback_model = fallback;
  }
  cfg.voice.fish = fish;
  writeConfig(cfg);
  return { ok: true, output: fallback ? `${model}, com ${fallback} se falhar` : `${model}, sem fallback` };
}

/* Default voice: the first of `voice.order`. The others stay as fallback, in the order
   they were. Applies to new videos and to those that didn't choose their own
   (`voice.provider` in scenes.json); one that already has lines doesn't regenerate. */
export const VOICE_PROVIDERS = ["elevenlabs", "fish", "cartesia", "voicestudio"];

export function setDefaultVoice(provider: unknown): Resp {
  const p = String(provider);
  if (!VOICE_PROVIDERS.includes(p)) return { ok: false, error: `provider desconhecido: ${provider}` };
  const cfg = readConfig();
  const order: string[] = cfg?.voice?.order ?? VOICE_PROVIDERS;
  if (order[0] === p) return { ok: true, output: "já era a padrão" };
  cfg.voice.order = [p, ...order.filter(x => x !== p), ...VOICE_PROVIDERS.filter(x => x !== p && !order.includes(x))];
  writeConfig(cfg);
  return {
    ok: true,
    output: `gravado: ${cfg.voice.order.join(" → ")}. Vale para vídeo novo e para o que não escolheu a voz`,
  };
}

/* cloned voice: on Fish the voice model's reference_id (32 hex), on Cartesia the voice id (UUID),
   on ElevenLabs the voice_id (20 alphanumeric chars) */
const VOICE_ID_FORMAT: Record<string, { re: RegExp; name: string }> = {
  fish: { re: /^[0-9a-f]{32}$/i, name: "32 caracteres hexadecimais" },
  cartesia: { re: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, name: "um UUID" },
  elevenlabs: { re: /^[A-Za-z0-9]{20}$/, name: "20 letras e números" },
};
const VOICE_ID_PROVIDER_NAME: Record<string, string> = { fish: "Fish", cartesia: "Cartesia", elevenlabs: "ElevenLabs" };

export function setVoiceId(provider: unknown, id: unknown): Resp {
  const format = VOICE_ID_FORMAT[String(provider)];
  if (!format) return { ok: false, error: `provider desconhecido: ${provider}` };
  const v = typeof id === "string" ? id.trim() : "";
  if (!format.re.test(v))
    return { ok: false, error: `o voice_id da ${VOICE_ID_PROVIDER_NAME[String(provider)]} é ${format.name}` };
  const cfg = readConfig();
  const p = cfg?.voice?.[provider as string];
  if (!p) return { ok: false, error: `omnivideo.config.json sem voice.${provider}` };
  if (p.voice_id === v) return { ok: true, output: "já era este" };
  cfg.voice[provider as string] = withKey(p, "voice_id", v, "key_env");
  writeConfig(cfg);
  return { ok: true, output: "gravado: vale para a próxima voz" };
}

/* --- voice profiles --------------------------------------------------------------------
   `voice.profiles`: each profile is a voice with a name, the providers it has (the Fish
   voice_id, the Cartesia one, the VoiceStudio profile name) and the attempt `order`
   among them: the first is preferred, the others are fallback. `voice.default_profile`
   is the id of the active voice, the one preselected on a new video. A video picks its own in
   `voice.voice_profile` of scenes.json (tools/voice.py resolves it). Without any profile, each
   provider's voice_id and `voice.order` apply. */
export type VoiceProfile = {
  id: string;
  name: string;
  order: string[];
  fish: string | null;
  cartesia: string | null;
  voicestudio: string | null;
  elevenlabs: string | null;
  /* the avatar seed (`h<hue>-<suffix>`), chosen when cloning; without it the id is used */
  avatar: string | null;
};

const AVATAR_RE = /^h\d{1,3}-[a-z0-9]{3,12}$/;

const profileSlug = (name: string) =>
  name
    .normalize("NFD")
    .replace(/[̀-ͯ]/g, "")
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 32);

/* the profile's order only has providers it configured; configured ones that are missing
   go at the end, in the default order */
function orderOf(
  profile: Pick<VoiceProfile, "fish" | "cartesia" | "voicestudio" | "elevenlabs">,
  requested: unknown,
): string[] {
  const has = (p: string) => !!profile[p as "fish" | "cartesia" | "voicestudio" | "elevenlabs"];
  const given = Array.isArray(requested)
    ? requested.map(String).filter(p => VOICE_PROVIDERS.includes(p) && has(p))
    : [];
  const unique = given.filter((p, i) => given.indexOf(p) === i);
  return [...unique, ...VOICE_PROVIDERS.filter(p => has(p) && !unique.includes(p))];
}

const profilesOf = (cfg: any): VoiceProfile[] =>
  ((cfg?.voice?.profiles ?? []) as any[]).map(p => {
    const base = {
      fish: p.fish ?? null,
      cartesia: p.cartesia ?? null,
      voicestudio: p.voicestudio ?? null,
      elevenlabs: p.elevenlabs ?? null,
    };
    const avatar = typeof p.avatar === "string" && AVATAR_RE.test(p.avatar) ? p.avatar : null;
    return { id: String(p.id), name: String(p.name ?? p.id), order: orderOf(base, p.order), ...base, avatar };
  });

export const getProfile = (id: unknown): VoiceProfile | undefined => profilesOf(readConfig()).find(p => p.id === id);

const toConfig = (p: VoiceProfile) => ({
  id: p.id,
  name: p.name,
  order: p.order,
  ...(p.fish ? { fish: p.fish } : {}),
  ...(p.cartesia ? { cartesia: p.cartesia } : {}),
  ...(p.voicestudio ? { voicestudio: p.voicestudio } : {}),
  ...(p.elevenlabs ? { elevenlabs: p.elevenlabs } : {}),
  ...(p.avatar ? { avatar: p.avatar } : {}),
});

/* one profile at a time: empty id creates (new id from the name), existing id edits */
export function saveProfile(data: {
  id?: unknown;
  name?: unknown;
  order?: unknown;
  fish?: unknown;
  cartesia?: unknown;
  voicestudio?: unknown;
  elevenlabs?: unknown;
  avatar?: unknown;
}): Resp & { id?: string } {
  const name = typeof data.name === "string" ? data.name.trim() : "";
  if (!name || name.length > 40) return { ok: false, error: "dê um nome à voz (até 40 caracteres)" };
  const str = (v: unknown) => (typeof v === "string" ? v.trim() : "");
  const fish = str(data.fish),
    cartesia = str(data.cartesia),
    voicestudio = str(data.voicestudio),
    elevenlabs = str(data.elevenlabs);
  if (!fish && !cartesia && !voicestudio && !elevenlabs)
    return { ok: false, error: "escolha ao menos um provedor e informe a voz dele" };
  if (fish && !VOICE_ID_FORMAT.fish.re.test(fish))
    return { ok: false, error: `o Voice ID da Fish é ${VOICE_ID_FORMAT.fish.name}` };
  if (cartesia && !VOICE_ID_FORMAT.cartesia.re.test(cartesia))
    return { ok: false, error: `o Voice ID da Cartesia é ${VOICE_ID_FORMAT.cartesia.name}` };
  if (elevenlabs && !VOICE_ID_FORMAT.elevenlabs.re.test(elevenlabs))
    return { ok: false, error: `o Voice ID da ElevenLabs é ${VOICE_ID_FORMAT.elevenlabs.name}` };
  if (voicestudio.length > 80)
    return { ok: false, error: "o nome do perfil no VoiceStudio é curto demais para ser real (até 80 caracteres)" };

  const cfg = readConfig();
  if (!cfg?.voice) return { ok: false, error: "omnivideo.config.json sem voice" };
  const profiles = profilesOf(cfg);
  const requested = str(data.id);
  const existing = requested ? profiles.find(p => p.id === requested) : undefined;
  if (requested && !existing) return { ok: false, error: `a voz “${requested}” não existe` };
  if (profiles.some(p => p.id !== requested && p.name.toLowerCase() === name.toLowerCase()))
    return { ok: false, error: `já existe uma voz chamada “${name}”` };

  let id = existing?.id ?? "";
  if (!id) {
    const base = profileSlug(name) || "voz";
    id = base;
    for (let n = 2; profiles.some(p => p.id === id); n++) id = `${base}-${n}`;
  }
  const voiceIds = {
    fish: fish || null,
    cartesia: cartesia || null,
    voicestudio: voicestudio || null,
    elevenlabs: elevenlabs || null,
  };
  /* without an avatar in the request (the editor doesn't send one), the voice keeps what it had */
  const avatar =
    typeof data.avatar === "string" && AVATAR_RE.test(data.avatar) ? data.avatar : (existing?.avatar ?? null);
  const item: VoiceProfile = { id, name, order: orderOf(voiceIds, data.order), ...voiceIds, avatar };
  const list = existing ? profiles.map(p => (p.id === id ? item : p)) : [...profiles, item];
  cfg.voice = withKey(cfg.voice, "profiles", list.map(toConfig), "order");
  /* the first voice created is already the active one: without this a new video would fall back to the loose voice_id */
  if (!cfg.voice.default_profile || !list.some(p => p.id === cfg.voice.default_profile))
    cfg.voice = withKey(cfg.voice, "default_profile", id, "profiles");
  writeConfig(cfg);
  generateSamples(item);
  return {
    ok: true,
    id,
    output: existing ? "gravado: vale para a próxima voz dos vídeos que usam esta voz" : "voz criada",
  };
}

/* "Ouvir voz": a short phrase in the voice of each of the profile's providers (tools/voice_sample.py).
   One sample per provider, in .voice-samples/<profile>-<provider>-<hash of voice_id and phrase>.wav:
   name, order and avatar are not part of the key, so only changing that provider's
   voice_id (or the phrase) makes a new one, and the same voice is never billed twice. The
   samples are generated in the background when the voice is created or edited; playing only regenerates
   if generation failed. */
export const SAMPLES_DIR = join(ROOT, ".voice-samples");
const PROVIDER_NAME: Record<string, string> = {
  fish: "Fish Audio",
  cartesia: "Cartesia",
  voicestudio: "VoiceStudio",
  elevenlabs: "ElevenLabs",
};
const SAMPLE_PHRASE = "Esta é a minha voz. É assim que eu vou narrar os seus vídeos.";
type Sample = { ok: true; url: string; provider: string } | { ok: false; error: string };
const inProgress = new Map<string, Promise<{ ok: true } | { ok: false; error: string }>>();

const sampleFile = (profile: VoiceProfile, provider: string) => {
  const key = createHash("sha1")
    .update(JSON.stringify({ provider, voice: (profile as any)[provider], phrase: SAMPLE_PHRASE }))
    .digest("hex")
    .slice(0, 10);
  return `${profile.id}-${provider}-${key}.wav`;
};

/* removes the profile's old samples (of `provider`, or all), except `keep` */
function clearSamples(id: string, provider?: string, keep?: string) {
  if (!existsSync(SAMPLES_DIR)) return;
  const re = new RegExp(`^${id}-(?:(?:${provider ?? VOICE_PROVIDERS.join("|")})-)?[0-9a-f]{10}\\.wav$`);
  for (const file of readdirSync(SAMPLES_DIR)) {
    if (file !== keep && re.test(file)) rmSync(join(SAMPLES_DIR, file), { force: true });
  }
}

async function providerSample(profile: VoiceProfile, provider: string): Promise<Sample> {
  if (!(profile as any)[provider])
    return { ok: false, error: `a voz “${profile.name}” não tem voz no ${PROVIDER_NAME[provider] ?? provider}` };
  const file = sampleFile(profile, provider);
  const dest = join(SAMPLES_DIR, file);
  const done: Sample = { ok: true, url: `/api/voice-sample/${file}`, provider };
  if (existsSync(dest)) return done;
  /* two requests for the same sample (the click and the background generation) wait on the same process */
  let p = inProgress.get(file);
  if (!p) {
    p = (async () => {
      mkdirSync(SAMPLES_DIR, { recursive: true });
      const r = await run([
        PYTHON,
        join(TOOLS_DIR, "voice_sample.py"),
        profile.id,
        dest,
        "--provider",
        provider,
        "--phrase",
        SAMPLE_PHRASE,
      ]);
      if (r.code !== 0)
        return { ok: false as const, error: r.stderr.trim().split("\n").pop() || "não consegui gerar a amostra" };
      clearSamples(profile.id, provider, file);
      return { ok: true as const };
    })().finally(() => inProgress.delete(file));
    inProgress.set(file, p);
  }
  const r = await p;
  return r.ok ? done : r;
}

/* empty `provider`: the voice as a video would use it, the first ready sample in the profile's order
   or, with none, the first that comes out (with fallback). With `provider`: only that one. */
export async function voiceSample(
  id: unknown,
  provider?: unknown,
): Promise<Resp & { url?: string; provider?: string }> {
  const profile = profilesOf(readConfig()).find(p => p.id === id);
  if (!profile) return { ok: false, error: "voz não encontrada" };
  if (provider !== undefined && provider !== null && provider !== "") {
    if (typeof provider !== "string" || !VOICE_PROVIDERS.includes(provider))
      return { ok: false, error: "provider desconhecido" };
    const r = await providerSample(profile, provider);
    return r.ok ? { ok: true, output: PROVIDER_NAME[provider], url: r.url, provider: r.provider } : r;
  }
  const withVoice = profile.order.filter(p => (profile as any)[p]);
  const ready = withVoice.find(p => existsSync(join(SAMPLES_DIR, sampleFile(profile, p))));
  const errors: string[] = [];
  for (const p of ready ? [ready] : withVoice) {
    const r = await providerSample(profile, p);
    if (r.ok) return { ok: true, output: PROVIDER_NAME[p], url: r.url, provider: p };
    errors.push(`${PROVIDER_NAME[p]}: ${r.error}`);
  }
  return { ok: false, error: errors.join(" · ") || "esta voz não tem nenhum provedor" };
}

/* in the background, one provider at a time: one without a key or not open fails right away and is left
   for the click */
function generateSamples(profile: VoiceProfile) {
  void (async () => {
    for (const p of profile.order) {
      if (!(profile as any)[p]) continue;
      const r = await providerSample(profile, p).catch(e => ({ ok: false as const, error: String(e?.message ?? e) }));
      if (!r.ok) console.error(`amostra da voz “${profile.name}” (${p}): ${r.error}`);
    }
  })();
}

export function setDefaultProfile(id: unknown): Resp {
  const cfg = readConfig();
  const profile = profilesOf(cfg).find(p => p.id === id);
  if (!profile) return { ok: false, error: "voz não encontrada" };
  if (cfg.voice.default_profile === profile.id) return { ok: true, output: "já era a voz ativa" };
  cfg.voice = withKey(cfg.voice, "default_profile", profile.id, "profiles");
  writeConfig(cfg);
  return { ok: true, output: `“${profile.name}” é a voz ativa: já vem marcada no vídeo novo` };
}

/* Deletes the voice on the provider's account. 404 counts as deleted (it wasn't there). Returns the error, or null. */
async function deleteOnProvider(
  provider: "fish" | "cartesia" | "elevenlabs",
  voiceId: string,
  cfg: any,
): Promise<string | null> {
  const key = providerKey(provider);
  if (!key) return "sem API key";
  const request: Record<typeof provider, [string, Record<string, string>]> = {
    fish: [`https://api.fish.audio/model/${voiceId}`, { Authorization: `Bearer ${key}` }],
    cartesia: [
      `https://api.cartesia.ai/voices/${voiceId}`,
      { Authorization: `Bearer ${key}`, "Cartesia-Version": cfg?.voice?.cartesia?.api_version ?? "2026-08-14" },
    ],
    elevenlabs: [`https://api.elevenlabs.io/v1/voices/${voiceId}`, { "xi-api-key": key }],
  };
  const [url, headers] = request[provider];
  try {
    const r = await fetch(url, { method: "DELETE", headers, signal: AbortSignal.timeout(30_000) });
    if (r.ok || r.status === 404) return null;
    return `respondeu ${r.status}: ${(await r.text()).replace(/\s+/g, " ").slice(0, 160)}`;
  } catch (e: any) {
    return e?.name === "TimeoutError" ? "não respondeu em 30 s" : String(e?.message ?? e);
  }
}

/* Redoing a voice: deletes the old one on the provider's account, after the new one is created. A Voice
   ID that another voice also uses, or that is the provider's loose voice_id in the config, stays. Returns the
   error (to delete by hand), or null when deleted or kept. */
export async function deleteOldVoice(
  profileId: string,
  provider: "fish" | "cartesia" | "elevenlabs",
  voiceId: string,
): Promise<string | null> {
  const cfg = readConfig();
  const others = profilesOf(cfg).filter(p => p.id !== profileId);
  if (others.some(o => o[provider] === voiceId) || cfg?.voice?.[provider]?.voice_id === voiceId) return null;
  return deleteOnProvider(provider, voiceId, cfg);
}

/* Removing the voice takes it out of the app and deletes it on the providers' accounts (Fish, Cartesia, ElevenLabs).
   VoiceStudio stays: its profile is local and serves other voices. A Voice ID that another voice
   also uses, or that is the provider's loose voice_id in the config, is not deleted. A provider failure
   doesn't block the removal: it goes in the result, to delete by hand. */
export async function removeProfile(id: unknown): Promise<Resp> {
  const cfg = readConfig();
  const profiles = profilesOf(cfg);
  const profile = profiles.find(p => p.id === id);
  if (!profile) return { ok: false, error: "voz não encontrada" };
  const rest = profiles.filter(p => p.id !== profile.id);

  const deleted: string[] = [],
    kept: string[] = [],
    failures: string[] = [];
  for (const p of ["fish", "cartesia", "elevenlabs"] as const) {
    const voiceId = profile[p];
    if (!voiceId) continue;
    if (rest.some(o => o[p] === voiceId) || cfg?.voice?.[p]?.voice_id === voiceId) {
      kept.push(PROVIDER_NAME[p]);
      continue;
    }
    const error = await deleteOnProvider(p, voiceId, cfg);
    if (error) failures.push(`${PROVIDER_NAME[p]} (${voiceId}): ${error}`);
    else deleted.push(PROVIDER_NAME[p]);
  }

  cfg.voice = withKey(cfg.voice, "profiles", rest.map(toConfig), "order");
  if (cfg.voice.default_profile === profile.id)
    cfg.voice = withKey(cfg.voice, "default_profile", rest[0]?.id ?? null, "profiles");
  writeConfig(cfg);
  clearSamples(profile.id);
  const parts = [`“${profile.name}” removida`];
  if (deleted.length) parts.push(`apagada na ${deleted.join(", na ")}`);
  if (kept.length) parts.push(`mantida na ${kept.join(", na ")}, porque outra voz usa o mesmo Voice ID`);
  if (failures.length) parts.push(`não deu para apagar na ${failures.join("; na ")}: apague à mão na conta`);
  return {
    ok: true,
    output: `${parts.join(". ")}. Vídeo que usava esta voz precisa escolher outra antes de gerar as falas`,
  };
}

/* Fish price used in the cost estimate (usage.fish.usd_per_million_bytes) */
export function setFishPrice(value: unknown): Resp {
  const n = typeof value === "number" ? value : Number(String(value).replace(",", "."));
  if (!Number.isFinite(n) || n < 0 || n > 10_000) return { ok: false, error: "preço inválido" };
  const cfg = readConfig();
  cfg.usage = cfg.usage ?? {};
  cfg.usage.fish = withKey(cfg.usage.fish ?? {}, "usd_per_million_bytes", n);
  writeConfig(cfg);
  return { ok: true, output: `US$ ${n} por milhão de bytes` };
}

/* Cartesia plan (usage.cartesia): the API only returns usage, never the plan, so the quota
   is the chosen plan's (tools/usage.py CARTESIA_PLANS) or, for "other", the one the user typed */
const CARTESIA_PLANS: Record<string, number> = { free: 20_000, pro: 100_000, startup: 1_250_000, scale: 8_000_000 };
export function setCartesiaPlan(plan: unknown, quota: unknown, day: unknown): Resp {
  const p = String(plan);
  if (!(p in CARTESIA_PLANS) && p !== "other") return { ok: false, error: "plano desconhecido" };
  const d = Number(day);
  if (!Number.isInteger(d) || d < 1 || d > 28) return { ok: false, error: "o dia da renovação é de 1 a 28" };
  const q = p === "other" ? Number(String(quota).replace(/\./g, "").replace(",", ".")) : CARTESIA_PLANS[p];
  if (!Number.isFinite(q) || q <= 0 || q > 1_000_000_000) return { ok: false, error: "cota inválida" };
  const cfg = readConfig();
  cfg.usage = cfg.usage ?? {};
  const current = cfg.usage.cartesia ?? {};
  cfg.usage.cartesia = withKey(
    withKey(withKey(current, "plan", p), "monthly_quota", Math.round(q), "plan"),
    "cycle_day",
    d,
  );
  writeConfig(cfg);
  return {
    ok: true,
    output: `${p === "other" ? "Outro plano" : `Plano ${p}`}: ${Math.round(q).toLocaleString("pt-BR")} créditos por mês, renova no dia ${d}`,
  };
}

/* --- agent accounts --------------------------------------------------------------------
   `agents.accounts` (N Claude config dirs, N Codex homes) and `agents.codex` (model, effort,
   sandbox); the rotation and the limits live in tools/lib/agents.mjs. With no list, the one account is the
   Claude Code this machine uses (~/.claude, or the folder the plugin's hook recorded). */
const SANDBOXES = ["auto", "full"];

function agentsSettings(cfg: any) {
  const accounts = accountsOf(cfg);
  const logins = loginRuns();
  return {
    accounts: accounts.map(a => ({
      id: a.id,
      provider: a.provider,
      dir: tildify(a.dir),
      label: a.label,
      enabled: a.enabled,
      login: loginOf(a),
      limited_until: limitedUntil(ROOT, a.id) || null,
      login_command: loginCommand(a, cfg),
      logging_in: logins[a.id] ?? null,
      implicit: a.implicit,
    })),
    /* who takes the next new session */
    next: pickAccount(ROOT, cfg, { advance: false })?.id ?? null,
    codex: {
      ...codexSettings(cfg),
      bin: codexBin(cfg),
      installed: existsSync(codexBin(cfg)) || !!Bun.which(codexBin(cfg)),
      options: { models: codexModels(accounts), sandboxes: SANDBOXES },
    },
  };
}

export function saveAgents(body: {
  accounts?: unknown;
  codex?: { model?: string; effort?: string; sandbox?: string };
}): Resp {
  const cfg = readConfig();
  const agents = { ...(cfg.agents ?? {}) };
  if (body.accounts !== undefined) {
    const c = cleanAccounts(body.accounts);
    if ("error" in c) return { ok: false, error: c.error as string };
    for (const a of c.accounts) mkdirSync(expandHome(a.dir), { recursive: true });
    agents.accounts = c.accounts;
  }
  if (body.codex) {
    const next = { ...(agents.codex ?? {}) };
    if (body.codex.sandbox !== undefined) {
      if (!SANDBOXES.includes(body.codex.sandbox))
        return { ok: false, error: `sandbox desconhecida: ${body.codex.sandbox}` };
      next.sandbox = body.codex.sandbox;
    }
    if (body.codex.model !== undefined) {
      if (!/^[\w.:-]+$/.test(body.codex.model)) return { ok: false, error: "modelo inválido" };
      next.model = body.codex.model;
    }
    if (body.codex.effort !== undefined) {
      if (body.codex.effort && !/^[a-z]+$/.test(body.codex.effort)) return { ok: false, error: "effort inválido" };
      if (body.codex.effort) next.effort = body.codex.effort;
      else delete next.effort;
    }
    agents.codex = next;
  }
  cfg.agents = agents;
  writeConfig(cfg);
  const n = accountsOf(cfg).length;
  return { ok: true, output: `${n} conta${n === 1 ? "" : "s"} de agente salva${n === 1 ? "" : "s"}` };
}

/* `claude auth login` / `codex login` for one account: each opens the browser and waits for the
   callback; the screen rereads the settings until the login shows up */
type LoginRun = { state: "waiting" | "ok" | "error"; url: string | null; output: string; at: number };
const logins: Record<string, { run: LoginRun; proc: ReturnType<typeof Bun.spawn> }> = {};
const loginRuns = () => Object.fromEntries(Object.entries(logins).map(([id, l]) => [id, l.run]));

export async function loginAgent(id: string): Promise<Resp & { url?: string | null }> {
  const cfg = readConfig();
  const a = accountsOf(cfg).find(x => x.id === id);
  if (!a) return { ok: false, error: "conta não encontrada" };
  logins[id]?.proc.kill();
  mkdirSync(a.dir, { recursive: true });
  const cmd = a.provider === "claude" ? [claudeBin(cfg), "auth", "login"] : [codexBin(cfg), "login"];
  const proc = Bun.spawn(cmd, { cwd: ROOT, stdin: "ignore", stdout: "pipe", stderr: "pipe", env: envFor(a) });
  const entry = { run: { state: "waiting", url: null, output: "", at: Date.now() } as LoginRun, proc };
  logins[id] = entry;
  const read = async (stream: ReadableStream<Uint8Array>) => {
    const dec = new TextDecoder();
    for await (const chunk of stream) {
      entry.run.output = (entry.run.output + dec.decode(chunk)).slice(-4000);
      entry.run.url ??= /https:\/\/\S+/.exec(entry.run.output)?.[0] ?? null;
    }
  };
  void read(proc.stdout as ReadableStream<Uint8Array>);
  void read(proc.stderr as ReadableStream<Uint8Array>);
  proc.exited.then(code => {
    if (logins[id] === entry) entry.run.state = code === 0 && loginOf(a) ? "ok" : "error";
  });
  /* the link shows up in a second or two; the browser usually opens by itself */
  for (let i = 0; i < 20 && !entry.run.url && entry.run.state === "waiting"; i++) await Bun.sleep(200);
  return {
    ok: true,
    output: entry.run.url ? "abri o login no navegador: entre e volte aqui" : "login iniciado: siga no navegador",
    url: entry.run.url,
  };
}

export function clearAgentLimit(id: string): Resp {
  return clearLimit(ROOT, id)
    ? { ok: true, output: "conta liberada: volta para o rodízio" }
    : { ok: false, error: "essa conta não está no limite" };
}

/* model and effort of a studio session: the orchestrator (video) or the reference */
export function sessionModel(type: string): { model?: string; effort?: string } | null {
  const m = readConfig()?.models;
  return (
    (type === "reference"
      ? m?.reference
      : type === "edit"
        ? (m?.edit ?? m?.orchestrator)
        : type === "omni"
          ? (m?.omni ?? m?.orchestrator)
          : m?.orchestrator) ?? null
  );
}

/* --- model and effort per stage ---------------------------------------------------------
   `models` in the config; the stages go to the skills' frontmatter (tools/models.mjs apply) */
type ModelChoice = { model: string; effort?: string };

export function saveModels(body: any): Resp {
  const cfg = readConfig();
  const current = cfg.models ?? { stages: {} };
  const clean = (m: any): ModelChoice | string => {
    const e: ModelChoice = { model: String(m?.model ?? "") };
    if (m?.effort) e.effort = String(m.effort);
    return validate(e) ?? e;
  };
  const next: any = { ...current, stages: { ...(current.stages ?? {}) } };
  for (const k of ["orchestrator", "reference"]) {
    if (body?.[k] == null) continue;
    const e = clean(body[k]);
    if (typeof e === "string") return { ok: false, error: `${k}: ${e}` };
    next[k] = e;
  }
  for (const [stage, m] of Object.entries(body?.stages ?? {})) {
    if (!(stage in next.stages)) return { ok: false, error: `etapa desconhecida: ${stage}` };
    const e = clean(m);
    if (typeof e === "string") return { ok: false, error: `${stage}: ${e}` };
    next.stages[stage] = e;
  }
  cfg.models = next;
  writeConfig(cfg);
  try {
    const changed = applyModels();
    return { ok: true, output: changed.length ? `gravado; skills atualizadas: ${changed.join(", ")}` : "gravado" };
  } catch (e: any) {
    return { ok: false, error: `a config foi gravada, mas as skills não: ${e.message}` };
  }
}

/* --- publishing ---------------------------------------------------------------------
   `publish` in the config: publish.mjs rereads it on every use. Each field has its
   validator; what the UI sends that isn't here is refused. */
const valid = (v: unknown) => ({ v });
const invalid = (e: string) => ({ e });
type Validator = (x: unknown) => { v: unknown } | { e: string };
const boolField =
  (name: string): Validator =>
  x =>
    typeof x === "boolean" ? valid(x) : invalid(`${name}: precisa ser true ou false`);
const textField =
  (name: string, max: number): Validator =>
  x =>
    typeof x === "string" && x.length <= max ? valid(x.trim()) : invalid(`${name}: texto de até ${max} caracteres`);
const PLATFORMS = ["youtube", "instagram", "tiktok"];
const TIKTOK_PRIVACIES = ["SELF_ONLY", "MUTUAL_FOLLOW_FRIENDS", "FOLLOWER_OF_CREATOR", "PUBLIC_TO_EVERYONE"];

const PUBLISH_SECTIONS: Record<string, Record<string, Validator>> = {
  auto: {
    approved: boolField("approved"),
    platforms: x =>
      Array.isArray(x) && x.every(p => PLATFORMS.includes(p))
        ? valid([...new Set(x)])
        : invalid("platforms: youtube, instagram e/ou tiktok"),
  },
  text: {
    footer_youtube: textField("footer_youtube", 2000),
    footer_instagram: textField("footer_instagram", 2000),
    footer_tiktok: textField("footer_tiktok", 2000),
    hashtags: x => {
      if (!Array.isArray(x) || x.length > 30) return invalid("hashtags: até 30");
      const l = x.map(h => String(h).trim().replace(/^#/, ""));
      return l.every(h => /^[\p{L}\p{N}_]+$/u.test(h)) ? valid(l) : invalid("hashtags: só letras, números e _");
    },
  },
  youtube: {
    privacy: x =>
      ["private", "unlisted", "public"].includes(String(x))
        ? valid(x)
        : invalid("privacy: private, unlisted ou public"),
    audited: boolField("audited"),
    category: x =>
      /^\d{1,3}$/.test(String(x)) ? valid(String(x)) : invalid("category: o número da categoria do YouTube"),
    language: x =>
      /^[a-z]{2,3}(-[A-Za-z0-9]{2,8})*$/.test(String(x)) ? valid(x) : invalid("language: algo como pt-BR"),
    made_for_kids: boolField("made_for_kids"),
    synthetic_content: boolField("synthetic_content"),
  },
  instagram: {
    api_version: x => (/^v\d{1,2}\.\d$/.test(String(x)) ? valid(x) : invalid("api_version: algo como v23.0")),
    share_to_feed: boolField("share_to_feed"),
    cover_at_s: x => {
      if (x === null || x === "") return valid(null);
      const n = Number(String(x).replace(",", "."));
      return Number.isFinite(n) && n >= 0 && n <= 900 ? valid(n) : invalid("cover_at_s: segundos de 0 a 900, ou vazio");
    },
  },
  tiktok: {
    mode: x => (["direct", "draft"].includes(String(x)) ? valid(x) : invalid("mode: direct ou draft")),
    privacy: x =>
      TIKTOK_PRIVACIES.includes(String(x)) ? valid(x) : invalid(`privacy: ${TIKTOK_PRIVACIES.join(", ")}`),
    audited: boolField("audited"),
    comments: boolField("comments"),
    duet: boolField("duet"),
    stitch: boolField("stitch"),
    ai_content: boolField("ai_content"),
    cover_at_s: x => {
      if (x === null || x === "") return valid(null);
      const n = Number(String(x).replace(",", "."));
      return Number.isFinite(n) && n >= 0 && n <= 600 ? valid(n) : invalid("cover_at_s: segundos de 0 a 600, ou vazio");
    },
  },
  schedule: {
    max_delay_h: x => {
      const n = Number(String(x).replace(",", "."));
      return Number.isFinite(n) && n >= 0.25 && n <= 168 ? valid(n) : invalid("max_delay_h: horas de 0,25 a 168");
    },
    attempts: x => {
      const n = Number(x);
      return Number.isInteger(n) && n >= 1 && n <= 10 ? valid(n) : invalid("attempts: de 1 a 10");
    },
    interval_min: x => {
      const n = Number(x);
      return Number.isInteger(n) && n >= 1 && n <= 120 ? valid(n) : invalid("interval_min: minutos de 1 a 120");
    },
  },
};

export function savePublishSettings(section: unknown, values: unknown): Resp {
  const fields = PUBLISH_SECTIONS[String(section)];
  if (!fields) return { ok: false, error: `seção desconhecida: ${section}` };
  if (!values || typeof values !== "object" || Array.isArray(values)) return { ok: false, error: "valores inválidos" };
  const cfg = readConfig();
  cfg.publish = cfg.publish ?? {};
  let obj: Record<string, unknown> = { ...(cfg.publish[section as string] ?? {}) };
  const changed: string[] = [];
  for (const [k, x] of Object.entries(values as Record<string, unknown>)) {
    const check = fields[k];
    if (!check) return { ok: false, error: `campo desconhecido: ${section}.${k}` };
    const r = check(x);
    if ("e" in r) return { ok: false, error: r.e };
    if (JSON.stringify(obj[k]) !== JSON.stringify(r.v)) changed.push(k);
    obj = withKey(obj, k, r.v);
  }
  if (section === "auto" && obj.approved === true && !(obj.platforms as string[] | undefined)?.length)
    return { ok: false, error: "escolha ao menos uma plataforma para a publicação automática" };
  if (!changed.length) return { ok: true, output: "já era assim" };
  cfg.publish[section as string] = obj;
  writeConfig(cfg);
  forgetAccounts();
  return { ok: true, output: `gravado: ${changed.join(", ")}` };
}

/* omnichat.instagram: enable the rule when the Reel goes up (the permanent approval to reply without
   the enable click) and whether a new rule quotes the Reel in the DM. Same defaults as omnichat.mjs */
const OMNICHAT_FIELDS: Record<string, Validator> = {
  enable_on_publish: boolField("enable_on_publish"),
  quote_post: boolField("quote_post"),
};

export function saveOmnichatSettings(values: unknown): Resp {
  if (!values || typeof values !== "object" || Array.isArray(values)) return { ok: false, error: "valores inválidos" };
  const cfg = readConfig();
  cfg.omnichat = cfg.omnichat ?? {};
  let obj: Record<string, unknown> = { ...(cfg.omnichat.instagram ?? {}) };
  const changed: string[] = [];
  for (const [k, x] of Object.entries(values as Record<string, unknown>)) {
    const check = OMNICHAT_FIELDS[k];
    if (!check) return { ok: false, error: `campo desconhecido: omnichat.${k}` };
    const r = check(x);
    if ("e" in r) return { ok: false, error: r.e };
    if (JSON.stringify(obj[k]) !== JSON.stringify(r.v)) changed.push(k);
    obj = withKey(obj, k, r.v);
  }
  if (!changed.length) return { ok: true, output: "já era assim" };
  cfg.omnichat.instagram = obj;
  writeConfig(cfg);
  return { ok: true, output: `gravado: ${changed.join(", ")}` };
}

/* Omni's voice (the agent page): the female or the male one; the voices themselves are
   `agent.voices` in the config */
export function setAgentGender(gender: unknown): Resp {
  if (gender !== "female" && gender !== "male") return { ok: false, error: "escolha voz feminina ou masculina" };
  const cfg = readConfig();
  if ((cfg.agent?.gender ?? "female") === gender) return { ok: true, output: "já era assim" };
  cfg.agent = { ...(cfg.agent ?? {}), gender };
  writeConfig(cfg);
  return { ok: true, output: gender === "male" ? "voz masculina" : "voz feminina" };
}

/* Omni's face: the seed of its avatar (the same kind a voice has), drawn by the studio */
export function setAgentAvatar(avatar: unknown): Resp {
  if (typeof avatar !== "string" || !AVATAR_SEED.test(avatar)) return { ok: false, error: "avatar inválido" };
  const cfg = readConfig();
  if (cfg.agent?.avatar === avatar) return { ok: true, output: "já era assim" };
  cfg.agent = { ...(cfg.agent ?? {}), avatar };
  writeConfig(cfg);
  return { ok: true, output: "avatar do Omni gravado" };
}

/* a provider's key as voice.py resolves it: the environment before .env */
export function providerKey(provider: "fish" | "cartesia" | "elevenlabs"): string | null {
  const fallback = { fish: "FISH_API_KEY", cartesia: "CARTESIA_API_KEY", elevenlabs: "ELEVENLABS_API_KEY" }[provider];
  const name = readConfig()?.voice?.[provider]?.key_env ?? fallback;
  return process.env[name] || readEnv()[name] || null;
}

export const profileNameExists = (name: string) =>
  profilesOf(readConfig()).some(p => p.name.toLowerCase() === name.trim().toLowerCase());

/* --- read for the UI ------------------------------------------------------------ */
export function getSettings() {
  const cfg = readConfig() ?? {};
  const env = readEnv();
  const fish = cfg.voice?.fish ?? {};
  const cartesia = cfg.voice?.cartesia ?? {};
  const elevenlabs = cfg.voice?.elevenlabs ?? {};
  const pub = cfg.publish ?? {};
  /* requires_approved_preview belonged to the preview stage, which no longer exists: left out so that
     saving the section doesn't send it back (it would be an unknown field) */
  const { requires_approved_preview: _dropped, ...auto } = pub.auto ?? {};
  return {
    voice: {
      order: (cfg.voice?.order ?? VOICE_PROVIDERS) as string[],
      profiles: profilesOf(cfg),
      voicestudio: { profile: cfg.voicestudio?.profile ?? null },
      default_profile: (cfg.voice?.default_profile ?? null) as string | null,
      fish: {
        key: keyStatus(fish.key_env ?? "FISH_API_KEY", env),
        voice_id: fish.voice_id ?? null,
        model: fish.model ?? "s2.1-pro-free",
        fallback_model: fish.fallback_model ?? null,
        usd_per_million_bytes: cfg.usage?.fish?.usd_per_million_bytes ?? null,
      },
      cartesia: {
        key: keyStatus(cartesia.key_env ?? "CARTESIA_API_KEY", env),
        admin_key: keyStatus(cfg.usage?.cartesia?.admin_key_env ?? "CARTESIA_ADMIN_API_KEY", env),
        voice_id: cartesia.voice_id ?? null,
        plan: (cfg.usage?.cartesia?.plan ?? "free") as string,
        monthly_quota: (cfg.usage?.cartesia?.monthly_quota ?? 20000) as number,
        cycle_day: (cfg.usage?.cartesia?.cycle_day ?? 1) as number,
      },
      elevenlabs: {
        key: keyStatus(elevenlabs.key_env ?? "ELEVENLABS_API_KEY", env),
        voice_id: elevenlabs.voice_id || null,
        model: elevenlabs.model ?? "eleven_multilingual_v2",
      },
    },
    /* the same defaults as publish.mjs */
    publish: {
      auto: { approved: false, platforms: [], ...auto },
      text: { footer_youtube: "", footer_instagram: "", footer_tiktok: "", hashtags: [], ...(pub.text ?? {}) },
      youtube: {
        privacy: "public",
        audited: false,
        category: "22",
        language: "pt-BR",
        made_for_kids: false,
        synthetic_content: false,
        ...(pub.youtube ?? {}),
      },
      instagram: { api_version: "v23.0", share_to_feed: true, cover_at_s: null, ...(pub.instagram ?? {}) },
      tiktok: {
        mode: "direct",
        privacy: "PUBLIC_TO_EVERYONE",
        audited: false,
        comments: true,
        duet: false,
        stitch: false,
        ai_content: true,
        cover_at_s: null,
        ...(pub.tiktok ?? {}),
      },
      schedule: { max_delay_h: 12, attempts: 3, interval_min: 10, ...(pub.schedule ?? {}) },
      keys: {
        youtube_client_id: keyStatus("YOUTUBE_CLIENT_ID", env),
        youtube_client_secret: keyStatus("YOUTUBE_CLIENT_SECRET", env),
        youtube_connected: !!env.YOUTUBE_REFRESH_TOKEN,
        instagram_connected: !!env.INSTAGRAM_TOKEN,
        tiktok_client_key: keyStatus("TIKTOK_CLIENT_KEY", env),
        tiktok_client_secret: keyStatus("TIKTOK_CLIENT_SECRET", env),
        tiktok_connected: !!env.TIKTOK_REFRESH_TOKEN,
      },
    },
    omnichat: {
      enable_on_publish: cfg.omnichat?.instagram?.enable_on_publish === true,
      quote_post: cfg.omnichat?.instagram?.quote_post !== false,
    },
    agents: agentsSettings(cfg),
    models: {
      orchestrator: cfg.models?.orchestrator ?? null,
      reference: cfg.models?.reference ?? null,
      stages: Object.entries(cfg.models?.stages ?? {}).map(([stage, m]: [string, any]) => ({
        stage,
        ...m,
        in_skill: inSkill(stage),
      })),
      options: { models: MODELS, efforts: EFFORTS },
    },
  };
}
