/**
 * taleb.ts — outlier-hunter detective.
 *
 * Given a topic, locates the most surprising chunks given the dominant
 * explanations. Writes each as a public.gaps row + case/gaps/G-NNNN.md.
 *
 * Workflow:
 *  1. hybridSearch shortlist (k=18, same as Dupin — outliers need
 *     dispersion).
 *  2. Claude reads + emits a JSON array of 0-3 outliers.
 *  3. writeOutlierGap() validates chunk_pk FK + persists.
 */
import { readFile } from "node:fs/promises";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { audit } from "../lib/audit";
import { callClaude } from "../lib/claude";
import { env } from "../lib/env";
import { hybridSearch, type SearchHit } from "../lib/search";
import { writeOutlierGap, type WriteOutlierGapArgs } from "../tools/write_outlier_gap";

const HERE = path.dirname(fileURLToPath(import.meta.url));
const PROMPT_PATH = path.resolve(HERE, "..", "..", "prompts", "taleb.md");

export interface TalebTask {
  job_id: string;
  topic: string;
  doc_id?: string;
  lang?: "pt" | "en";
  context_chunks?: number;
  budget_cap_usd?: number;
}

function renderChunkBlock(hits: SearchHit[], lang: "pt" | "en"): string {
  return hits.map((h, i) => {
    const text = (lang === "en" ? h.content_en : h.content_pt) || h.content_en || h.content_pt || "";
    return [
      `--- chunk ${i + 1} ---`,
      `doc_id: ${h.doc_id}`,
      `chunk_id: ${h.chunk_id}`,
      `page: ${h.page}`,
      `type: ${h.type}`,
      h.classification ? `classification: ${h.classification}` : null,
      "",
      text.slice(0, 1100),
    ].filter(Boolean).join("\n");
  }).join("\n\n");
}

function buildPrompt(task: TalebTask, hits: SearchHit[], lang: "pt" | "en"): string {
  return [
    `# Topic to scan for outliers`,
    "",
    task.topic,
    "",
    `## Corpus shortlist (${hits.length} chunks${task.doc_id ? `, scoped to ${task.doc_id}` : ""})`,
    "",
    renderChunkBlock(hits, lang),
    "",
    "## Your task",
    "",
    "Identify AT MOST 3 outliers per the system prompt rules. State the",
    "dominant_model first, then the chunk that violates it. Emit the",
    "JSON array exactly as specified — no prose, no code fence.",
    "**Bilingual is mandatory:** every narrative field appears in both",
    "EN and PT-BR. If nothing genuinely stands out, emit `NO_OUTLIERS`.",
  ].join("\n");
}

function extractJsonArray(text: string): unknown[] | null {
  const t = text.trim();
  if (/^`?NO_OUTLIERS`?\b/i.test(t)) return null;
  const stripped = t.replace(/^```(?:json)?\s*\n?/i, "").replace(/\n?```\s*$/i, "");
  const first = stripped.indexOf("[");
  const last = stripped.lastIndexOf("]");
  if (first === -1 || last === -1) {
    throw new Error(`taleb returned no JSON array: ${t.slice(0, 200)}`);
  }
  const parsed = JSON.parse(stripped.slice(first, last + 1));
  if (!Array.isArray(parsed)) throw new Error("taleb JSON is not an array");
  return parsed;
}

export async function runTaleb(task: TalebTask): Promise<
  | { outliers: Array<{ gap_id: string; case_file: string }> }
  | { skipped: true; reason: string }
> {
  const lang: "pt" | "en" = task.lang ?? "pt";
  const k = task.context_chunks ?? 18;

  let hits = await hybridSearch({
    query: task.topic, lang,
    doc_id: task.doc_id ?? null,
    top_k: k, recall_k: 80,
  });
  let scope_widened = false;
  if (task.doc_id && hits.length < 3) {
    const widened = await hybridSearch({
      query: task.topic, lang, doc_id: null, top_k: k, recall_k: 80,
    });
    if (widened.length > hits.length) {
      hits = widened;
      scope_widened = true;
    }
  }

  await audit({
    event: "taleb_grounded",
    job_id: task.job_id,
    detective: "taleb@detective",
    topic: task.topic,
    n_chunks: hits.length,
    doc_id: task.doc_id ?? null,
    scope_widened,
  });

  if (hits.length < 3) {
    return { skipped: true, reason: "insufficient_corpus" };
  }

  const systemPrompt = await readFile(PROMPT_PATH, "utf-8");
  const prompt = buildPrompt(task, hits, lang);
  const llm = await callClaude({
    prompt, systemPrompt,
    model: env.CLAUDE_MODEL,
    allowedTools: [],
    timeoutMs: env.JOB_TIMEOUT_SECONDS * 1000,
    budgetCapUsd: task.budget_cap_usd ?? env.BUDGET_CAP_USD_PER_JOB,
  });
  await audit({
    event: "detective_completed",
    job_id: task.job_id,
    detective: "taleb@detective",
    cost_usd: llm.costUsd,
    tokens_in: llm.tokensIn,
    tokens_out: llm.tokensOut,
    duration_ms: llm.durationMs,
  });
  console.error(`[taleb] response (${llm.text.length} chars): ${llm.text.slice(0, 600)}`);

  const arr = extractJsonArray(llm.text);
  if (arr === null) return { skipped: true, reason: "NO_OUTLIERS" };

  const out: Array<{ gap_id: string; case_file: string }> = [];
  for (const raw of arr.slice(0, 3)) {
    if (!raw || typeof raw !== "object") continue;
    const o = raw as Record<string, unknown>;
    const str = (k: string): string =>
      typeof o[k] === "string" ? (o[k] as string).trim() : "";
    const args: WriteOutlierGapArgs = {
      title:                      str("title"),
      title_pt_br:                str("title_pt_br"),
      doc_id:                     str("doc_id"),
      chunk_id:                   str("chunk_id"),
      dominant_model:             str("dominant_model"),
      dominant_model_pt_br:       str("dominant_model_pt_br"),
      why_surprising:             str("why_surprising"),
      why_surprising_pt_br:       str("why_surprising_pt_br"),
      what_it_implies:            str("what_it_implies"),
      what_it_implies_pt_br:      str("what_it_implies_pt_br"),
      suggested_next_move:        str("suggested_next_move"),
      suggested_next_move_pt_br:  str("suggested_next_move_pt_br"),
    };
    const argsAny = args as unknown as Record<string, unknown>;
    const missing = [
      "title", "title_pt_br", "doc_id", "chunk_id",
      "dominant_model", "dominant_model_pt_br",
      "why_surprising", "why_surprising_pt_br",
      "what_it_implies", "what_it_implies_pt_br",
      "suggested_next_move", "suggested_next_move_pt_br",
    ].filter((k) => !argsAny[k]);
    if (missing.length > 0) {
      await audit({
        event: "write_outlier_gap_failed",
        job_id: task.job_id, detective: "taleb@detective",
        reason: "incomplete_bilingual_outlier",
        missing, title: args.title.slice(0, 120),
      });
      continue;
    }
    try {
      const r = await writeOutlierGap(args, { job_id: task.job_id, detective: "taleb@detective" });
      out.push(r);
    } catch (e) {
      await audit({
        event: "write_outlier_gap_failed",
        job_id: task.job_id, detective: "taleb@detective",
        error: (e as Error).message, title: args.title.slice(0, 120),
      });
    }
  }
  return { outliers: out };
}
