import { createAdminClient } from "@/lib/supabase/admin";

export interface Persona {
  id: string;
  slug: string;
  name: string;
  gender: string | null;
  beat: string | null;
  avatar_url: string | null;
  bio: string | null;
  writing_style: string | null;
  active: boolean;
}

export async function listPersonas(activeOnly = true): Promise<Persona[]> {
  const sb = createAdminClient();
  const q = sb.from("ai_personas").select("*");
  const { data, error } = activeOnly ? await q.eq("active", true) : await q;
  if (error) throw new Error(`listPersonas: ${error.message}`);
  return (data || []) as Persona[];
}

export async function getPersonaBySlug(slug: string): Promise<Persona | null> {
  const sb = createAdminClient();
  const { data, error } = await sb.from("ai_personas").select("*").eq("slug", slug).maybeSingle();
  if (error) throw new Error(`getPersonaBySlug: ${error.message}`);
  return (data as Persona) || null;
}

export async function pickPersonaForContent(text: string): Promise<Persona> {
  const all = await listPersonas(true);
  if (all.length === 0) throw new Error("No active personas in bb.ai_personas");

  const haystack = text.toLowerCase();
  const beatScores: Record<string, number> = {
    "industry-veteran": 0,
    "streaming-ott": 0,
    "protocols-specs": 0,
    "business-m-and-a": 0,
    "live-sports": 0,
    "post-production": 0,
  };

  const cues: Record<string, string[]> = {
    "streaming-ott": ["streaming", "ott", "cdn", "drm", "encoder", "transcode", "hls", "dash", "vod"],
    "protocols-specs": ["st 2110", "smpte", "ndi", "jpeg xs", "rist", "srt", "protocol", "spec", "rfc"],
    "business-m-and-a": ["acquisition", "merger", "acquir", "valuation", "earnings", "revenue", "ceo", "cfo", "ipo", "layoff", "raised", "series"],
    "live-sports": ["live", "sports", "premier league", "nfl", "nba", "super bowl", "olympic", "remi", "ob truck", "world feed", "stadium"],
    "post-production": ["post-production", "post production", "color grade", "edit", "vfx", "render", "aces", "dailies", "virtual production", "mam"],
    "industry-veteran": ["legacy", "sdi", "baseband", "router", "frame sync", "infrastructure", "plant"],
  };

  for (const [beat, words] of Object.entries(cues)) {
    for (const w of words) {
      if (haystack.includes(w)) beatScores[beat] += 1;
    }
  }

  let bestBeat = "industry-veteran";
  let bestScore = -1;
  for (const [beat, score] of Object.entries(beatScores)) {
    if (score > bestScore) {
      bestScore = score;
      bestBeat = beat;
    }
  }

  const match = all.find((p) => p.beat === bestBeat);
  if (match) return match;
  return all[Math.floor(Math.random() * all.length)];
}
