/* Settings editable from the /settings screen. They live in two places: omnivideo.config.json (voice, prices, Claude models, the agent accounts…) and .env (the API
   keys, which never go back whole to the UI). The rules and the files are tools/lib/settings.mjs, which the agent also runs to answer the hosted page
   (so the page reads and writes the same thing from either); this file binds it to this workspace and keeps what only the studio's own process knows:
   the agent logins in progress. tools/voice.py rereads both on every `voice`; the studio rereads the config on every session. */

import { type Proc, sleep, spawn } from "../lib/runtime";
import { mkdirSync } from "node:fs";
import * as modelsLib from "../../../tools/models.mjs";
import { accountsOf, claudeBin, clearSignedOut, codexBin, envFor, loginOf } from "../../../tools/lib/agents.mjs";
import { createSettings, profilesOf as profilesOfLib } from "../../../tools/lib/settings.mjs";
import { PYTHON, ROOT, TOOLS_DIR, channelId, channelRoot, run } from "./root";
import { forgetUsage } from "./usage";
import { forgetAccounts } from "./publish";
import type { KeyStatus } from "../../shared/types/api";

type Resp = { ok: true; output: string } | { ok: false; error: string };
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;
};

/* One instance per channel, on that channel's folder: tools/lib/settings.mjs reads and writes the config and the .env through
   tools/lib/config.mjs, so a channel's voice, publishing and tokens land in the channel and the account's keys in the workspace. */
const byChannel = new Map<string, ReturnType<typeof createSettings>>();
/** the settings of channel `id` (the request's by default), for the other services that stand on the same rules (the voice clone) */
export function settingsOf(id: string = channelId()) {
  let lib = byChannel.get(id);
  if (!lib) {
    lib = createSettings({
      root: channelRoot(id),
      python: PYTHON,
      tools: TOOLS_DIR,
      run,
      models: modelsLib as never,
      /* the config or .env changed: the usage and the accounts are asked again */
      onWrite: () => {
        forgetUsage();
        forgetAccounts();
      },
    });
    byChannel.set(id, lib);
  }
  return lib;
}
export const readConfig = () => settingsOf().readConfig();
export const writeConfig = (cfg: unknown) => settingsOf().writeConfig(cfg);
export const readEnv = () => settingsOf().readEnv();
export { ENV_KEYS, FISH_MODELS, VOICE_PROVIDERS } from "../../../tools/lib/settings.mjs";
export const saveKey = (name: unknown, value: unknown) => settingsOf().saveKey(name, value) as Resp;
export const keyStatusOf = (name: string): KeyStatus => settingsOf().keyStatusOf(name);
export const setFishModel = (model: unknown, fallback: unknown) => settingsOf().setFishModel(model, fallback) as Resp;
export const setDefaultVoice = (provider: unknown) => settingsOf().setDefaultVoice(provider) as Resp;
export const setVoiceId = (provider: unknown, id: unknown) => settingsOf().setVoiceId(provider, id) as Resp;
export const profilesOf = (cfg: any): VoiceProfile[] => profilesOfLib(cfg);
export const getProfile = (id: unknown): VoiceProfile | undefined => settingsOf().getProfile(id);
/** the current channel's voice samples (.voice-samples) */
export const samplesDir = (): string => settingsOf().SAMPLES_DIR;
export const profileNameExists = (name: string) => settingsOf().profileNameExists(name);
export const providerKey = (provider: "fish" | "cartesia" | "elevenlabs"): string | null =>
  settingsOf().providerKey(provider);

/* one profile at a time: empty id creates (new id from the name), existing id edits; the samples are made in the background */
export function saveProfile(data: Record<string, unknown>): Resp & { id?: string } {
  const r = settingsOf().saveProfile(data);
  if (r.ok && r.profile) void settingsOf().generateSamples(r.profile);
  return r.ok ? { ok: true, id: r.id, output: r.output } : r;
}
export const voiceSample = (id: unknown, provider?: unknown): Promise<Resp & { url?: string; provider?: string }> =>
  settingsOf().voiceSample(id, provider);
export const setDefaultProfile = (id: unknown) => settingsOf().setDefaultProfile(id) as Resp;
export const deleteOldVoice = (profileId: string, provider: "fish" | "cartesia" | "elevenlabs", voiceId: string) =>
  settingsOf().deleteOldVoice(profileId, provider, voiceId);
export const removeProfile = (id: unknown): Promise<Resp> => settingsOf().removeProfile(id);
export const setFishPrice = (value: unknown) => settingsOf().setFishPrice(value) as Resp;
export const setCartesiaPlan = (plan: unknown, quota: unknown, day: unknown) =>
  settingsOf().setCartesiaPlan(plan, quota, day) as Resp;
export const saveAgents = (body: {
  accounts?: unknown;
  codex?: { model?: string; effort?: string; sandbox?: string };
}) => settingsOf().saveAgents(body) as Resp;
export const clearAgentLimit = (id: string) => settingsOf().clearAgentLimit(id) as Resp;
/* the model of a session of channel `channel` (each channel has its own models) */
export const sessionModel = (type: string, channel?: string): { model?: string; effort?: string } | null =>
  settingsOf(channel).sessionModel(type);
export const saveModels = (body: any) => settingsOf().saveModels(body) as Resp;
export const savePublishSettings = (section: unknown, values: unknown) =>
  settingsOf().savePublishSettings(section, values) as Resp;
export const saveOmnichatSettings = (values: unknown) => settingsOf().saveOmnichatSettings(values) as Resp;
export const saveSoundSettings = (values: unknown) => settingsOf().saveSoundSettings(values) as Resp;
export const saveImageSettings = (values: unknown) => settingsOf().saveImageSettings(values) as Resp;
export const indexSoundLibrary = () => settingsOf().indexSoundLibrary() as Resp & { count?: number };
export const pickSoundLibrary = () =>
  settingsOf().pickSoundLibrary() as Promise<Resp & { cancelled?: boolean; count?: number }>;
export const setAgentGender = (gender: unknown) => settingsOf().setAgentGender(gender) as Resp;
export const setAgentAutonomy = (autonomy: unknown) => settingsOf().setAgentAutonomy(autonomy) as Resp;
export const setAgentAvatar = (avatar: unknown) => settingsOf().setAgentAvatar(avatar) as Resp;

/* `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: Proc }> = {};
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 = 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) return;
    entry.run.state = code === 0 && loginOf(a) ? "ok" : "error";
    if (entry.run.state === "ok") clearSignedOut(ROOT, id);
  });
  /* 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 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,
  };
}

/* read for the UI */
export const getSettings = () => settingsOf().getSettings({ logins: loginRuns() });
