/* Typed decisions (System One: noul, choice, score) over text and images, for the Omni voice agent.
   Two models behind one call, routed by size: clef-flash straight on Workers AI for short text and
   images (fastest, ~0.2 s for a sentence), Jev 1.14 through OpenRouter for long text (262K context,
   steady ~0.6 s). Each is the other's fallback when a call fails or times out. Both speak the same
   question format, so the caller never knows which one answered, except through `model`. */

import { hashKey, spawn } from "../lib/runtime";
import { mkdirSync, readFileSync, existsSync, statSync } from "node:fs";
import { tmpdir } from "node:os";
import { extname, join } from "node:path";
import { readEnvKeys } from "./services";
import { aiFetch, aiProblem } from "./ai";

export type Question = {
  type: "noul" | "choice" | "score";
  instructions: string;
  criteria?: Record<string, string | null> | string[];
};
export type Answer =
  | { type: "noul"; noul: number }
  | { type: "choice"; choice: string; probabilities: Record<string, number>; confidence?: number }
  | { type: "score"; score: number; probabilities?: Record<string, number> };

export type ClassifyInput = {
  state: string;
  /* absolute paths of PNG/JPEG/WebP files */
  images?: string[];
  questions: Record<string, Question>;
  /* skip the router (tests, A/B) */
  model?: Model;
};
export type ClassifyResult =
  | {
      ok: true;
      answers: Record<string, Answer>;
      model: Model;
      ms: number;
      input_tokens: number;
      cost_usd: number;
      /* the model that failed before this one answered */
      fallback_from?: Model;
    }
  | { ok: false; error: string };

export type Model = "clef-flash" | "jev-1.14";

/* $ per input token (output is free on both) */
const PRICE: Record<Model, number> = { "clef-flash": 0.038 / 1e6, "jev-1.14": 0.042 / 1e6 };
/* clef-flash's window is 24,576 tokens and it silently truncates `state` past it: anything that may
   not fit goes to Jev. ~3.5 characters per token in Portuguese, ~1,100 tokens per image. */
const CLEF_MAX_TOKENS = 20_000;
const CLEF_MAX_IMAGES = 4;
const TIMEOUT_MS = 10_000;

export const estimateTokens = (state: string, images = 0) => Math.ceil(state.length / 3.5) + images * 1_100;

export function route(input: ClassifyInput): Model {
  if (input.model) return input.model;
  const images = input.images?.length ?? 0;
  if (images > CLEF_MAX_IMAGES) return "jev-1.14";
  return estimateTokens(input.state, images) > CLEF_MAX_TOKENS ? "jev-1.14" : "clef-flash";
}

export async function classify(input: ClassifyInput): Promise<ClassifyResult> {
  if (!Object.keys(input.questions).length) return { ok: false, error: "nenhuma pergunta" };
  for (const path of input.images ?? [])
    if (!existsSync(path)) return { ok: false, error: `imagem não encontrada: ${path}` };
  const first = route(input);
  const second: Model = first === "clef-flash" ? "jev-1.14" : "clef-flash";
  const a = await callModel(first, input);
  if (a.ok) return a;
  /* clef-flash can't take more than 4 images or a long text: then there is no fallback */
  const fits =
    second === "jev-1.14" ||
    ((input.images?.length ?? 0) <= CLEF_MAX_IMAGES &&
      estimateTokens(input.state, input.images?.length) <= CLEF_MAX_TOKENS);
  if (!fits) return a;
  const b = await callModel(second, input);
  return b.ok ? { ...b, fallback_from: first } : { ok: false, error: `${first}: ${a.error} · ${second}: ${b.error}` };
}

async function callModel(model: Model, input: ClassifyInput): Promise<ClassifyResult> {
  const t0 = performance.now();
  try {
    const r = model === "clef-flash" ? await callClef(input) : await callJev(input);
    const ms = Math.round(performance.now() - t0);
    return { ok: true, answers: r.answers, model, ms, input_tokens: r.tokens, cost_usd: r.tokens * PRICE[model] };
  } catch (e) {
    return { ok: false, error: String((e as Error)?.message ?? e) };
  }
}

type Raw = { answers: Record<string, Answer>; tokens: number };

async function post(provider: "cf" | "openrouter", url: string, body: unknown): Promise<any> {
  const r = await aiFetch(provider, url, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
    signal: AbortSignal.timeout(TIMEOUT_MS),
  });
  const text = await r.text();
  let json: any = null;
  try {
    json = JSON.parse(text);
  } catch {
    /* not JSON: the status says it */
  }
  if (!r.ok) {
    const message = json?.errors?.[0]?.message ?? json?.error?.message ?? json?.error ?? text.slice(0, 200);
    throw new Error(`${r.status} ${typeof message === "string" ? message : JSON.stringify(message)}`);
  }
  return json;
}

/* Workers AI REST: images go in their own `images` array as data URLs */
async function callClef(input: ClassifyInput): Promise<Raw> {
  const problem = aiProblem("cf");
  if (problem) throw new Error(problem);
  const body = {
    model: "clef-flash",
    state: input.state,
    questions: input.questions,
    ...(input.images?.length ? { images: input.images.map(dataUrl) } : {}),
  };
  /* the account is the Worker's; on this side only the path counts (ai.ts), and in development the .env's */
  const account = readEnvKeys().CLOUDFLARE_ACCOUNT_ID || "app";
  const j = await post(
    "cf",
    `https://api.cloudflare.com/client/v4/accounts/${account}/ai/run/@cf/cloudflare/clef-flash`,
    body,
  );
  const out = j?.result ?? j;
  if (!out?.answers) throw new Error("resposta sem answers");
  return { answers: out.answers, tokens: out.usage?.input_tokens ?? out.usage?.prompt_tokens ?? 0 };
}

/* OpenRouter Decisions API: images are parts of the `state` array; Jev wants PNG/JPEG with each side
   between 256 and 1,568 px, so larger files are resized (sips) into a cache first */
async function callJev(input: ClassifyInput): Promise<Raw> {
  const problem = aiProblem("openrouter");
  if (problem) throw new Error(problem);
  const images = await Promise.all((input.images ?? []).map(jevImage));
  const state = images.length
    ? [input.state, ...images.map(p => ({ type: "image_url", image_url: { url: dataUrl(p) } }))]
    : input.state;
  const j = await post("openrouter", "https://openrouter.ai/api/alpha/decisions", {
    model: "typesafe/jev-1.14",
    state,
    questions: input.questions,
  });
  if (!j?.answers) throw new Error("resposta sem answers");
  return { answers: j.answers, tokens: j.usage?.input_tokens ?? 0 };
}

const MIME: Record<string, string> = {
  ".png": "image/png",
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".webp": "image/webp",
};

function dataUrl(path: string) {
  const mime = MIME[extname(path).toLowerCase()] ?? "image/png";
  return `data:${mime};base64,${readFileSync(path).toString("base64")}`;
}

const JEV_CACHE = join(tmpdir(), "omnivideo-classify");
const JEV_MAX_SIDE = 1568;

async function jevImage(path: string): Promise<string> {
  const ext = extname(path).toLowerCase();
  const { width, height } = await imageSize(path);
  if ((ext === ".png" || ext === ".jpg" || ext === ".jpeg") && Math.max(width, height) <= JEV_MAX_SIDE) return path;
  mkdirSync(JEV_CACHE, { recursive: true });
  const out = join(JEV_CACHE, `${hashKey(`${path}:${statSync(path).mtimeMs}`)}.jpg`);
  if (!existsSync(out)) {
    const p = spawn(
      ["sips", "-s", "format", "jpeg", "-s", "formatOptions", "85", "-Z", String(JEV_MAX_SIDE), path, "--out", out],
      {
        stdout: "ignore",
        stderr: "pipe",
      },
    );
    if ((await p.exited) !== 0) throw new Error(`sips: ${await new Response(p.stderr).text()}`);
  }
  return out;
}

async function imageSize(path: string): Promise<{ width: number; height: number }> {
  const p = spawn(["sips", "-g", "pixelWidth", "-g", "pixelHeight", path], { stdout: "pipe", stderr: "ignore" });
  const text = await new Response(p.stdout).text();
  await p.exited;
  return {
    width: Number(/pixelWidth: (\d+)/.exec(text)?.[1] ?? 0),
    height: Number(/pixelHeight: (\d+)/.exec(text)?.[1] ?? 0),
  };
}
