/**
 * Module 11 AI (SOC-AI-001…009). Every model call goes through the gateway (credits, logs, fallback).
 * Guardrails: never invent prices/discounts not in the knowledge base, never reply publicly to complaints
 * or legal threats, never put personal data in a public reply. Low-confidence or risky replies go to the
 * AI approval queue instead of being sent.
 */
import { and, asc, desc, eq, isNull, or } from "drizzle-orm";
import { schema } from "@/db";
import type { Ctx } from "@/lib/auth";
import { ApiError } from "@/lib/api";
import { fullName } from "@/lib/util";
import { complete, parseJson, aiConfigured } from "./gateway";
import { classify, detectLanguage, extractEmails, extractPhones, type Classification } from "@/lib/services/social-text";
import type { RuleEvent } from "@/lib/services/social";
import { industryOf } from "@/lib/industry";

type By = { type: "user" | "rule" | "ai"; userId?: string | null; ruleId?: string; name?: string };
export type Suggestion = { text: string; confidence: number; language: string; grounded: string[]; publicSafe: boolean; reason?: string };

const RISKY_INTENTS = ["complaint", "legal"];
const LEGAL = /\b(lawyer|legal action|sue|court|police|consumer rights|উকিল|মামলা|আদালত|পুলিশ|ভোক্তা অধিকার)\b/i;
const MONEY = /(৳|tk\.?|taka|bdt|\$|lakh|lac|crore|লাখ|কোটি|টাকা|\d+\s?%|discount|ছাড়)/i;

/* ---------------- knowledge retrieval (SOC-AI-003) ---------------- */

const tokens = (s: string) => new Set(s.toLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").split(/\s+/).filter((w) => w.length > 2));

export async function retrieveKnowledge(ctx: Pick<Ctx, "db" | "workspace">, text: string, opts: { accountId?: string | null; scope?: string | null; limit?: number } = {}) {
  const rows = await ctx.db.select().from(schema.knowledgeEntries).where(and(eq(schema.knowledgeEntries.workspaceId, ctx.workspace.id), eq(schema.knowledgeEntries.isActive, true),
    opts.accountId ? or(isNull(schema.knowledgeEntries.socialAccountId), eq(schema.knowledgeEntries.socialAccountId, opts.accountId)) : undefined));
  const q = tokens(text);
  return rows.map((r) => {
    const t = tokens(`${r.question} ${r.tags.join(" ")} ${r.scope ?? ""}`);
    let score = 0;
    for (const w of q) if (t.has(w)) score += 1;
    if (opts.scope && r.scope && r.scope.toLowerCase() === opts.scope.toLowerCase()) score += 1.5;
    return { entry: r, score: score / Math.max(3, Math.sqrt(t.size)) };
  }).filter((x) => x.score > 0).sort((a, b) => b.score - a.score).slice(0, opts.limit ?? 5);
}

/* ---------------- classification (SOC-AI-001) ---------------- */

export async function classifyComment(ctx: Ctx, commentId: string) {
  const c = await ctx.db.query.comments.findFirst({ where: and(eq(schema.comments.id, commentId), eq(schema.comments.workspaceId, ctx.workspace.id)) });
  if (!c) return null;
  const base = classify(c.body);
  if (!aiConfigured()) return base;
  try {
    const { text } = await complete(ctx, {
      feature: "social_classify", tier: "fast", maxTokens: 300,
      system: "Classify a social media comment/DM for a Bangladeshi marketing & sales team. Text may be English, Bangla script or Banglish. Respond with JSON only: {\"intent\":\"price_inquiry|location_inquiry|booking|interested|support|complaint|thanks|spam|legal|other\",\"sentiment\":\"positive|neutral|negative\",\"language\":\"en|bn|banglish\",\"urgency\":\"low|normal|high\",\"toxicity\":0-1,\"lead_intent\":true|false}.",
      messages: [{ role: "user", content: c.body.slice(0, 2000) }],
    });
    const j = parseJson<{ intent: string; sentiment: string; language: string; urgency: string; toxicity: number; lead_intent: boolean }>(text);
    if (!j) return base;
    await ctx.db.update(schema.comments).set({ intent: j.intent ?? c.intent, sentiment: j.sentiment ?? c.sentiment, language: j.language ?? c.language, toxicity: typeof j.toxicity === "number" ? j.toxicity : c.toxicity }).where(eq(schema.comments.id, c.id));
    const conv = await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, c.conversationId) });
    if (conv) await ctx.db.update(schema.conversations).set({ intent: j.intent ?? conv.intent, sentiment: j.sentiment ?? conv.sentiment, ...(j.urgency === "high" && conv.priority === "normal" ? { priority: "high" } : {}) }).where(eq(schema.conversations.id, conv.id));
    return { ...base, intent: j.intent, sentiment: j.sentiment as Classification["sentiment"], language: j.language as Classification["language"] };
  } catch {
    return base; // rules-based classification already stored at ingest
  }
}

/* ---------------- context ---------------- */

async function threadContext(ctx: Ctx, conversationId: string) {
  const conv = await ctx.db.query.conversations.findFirst({ where: and(eq(schema.conversations.id, conversationId), eq(schema.conversations.workspaceId, ctx.workspace.id)) });
  if (!conv) throw new ApiError(404, "not_found", "Conversation not found");
  const contact = await ctx.db.query.contacts.findFirst({ where: eq(schema.contacts.id, conv.contactId) });
  const obj = conv.socialObjectId ? await ctx.db.query.socialObjects.findFirst({ where: eq(schema.socialObjects.id, conv.socialObjectId) }) : null;
  let transcript: { who: "customer" | "brand" | "note"; text: string }[] = [];
  if (conv.kind === "comment_thread") {
    const cs = await ctx.db.select().from(schema.comments).where(eq(schema.comments.conversationId, conv.id)).orderBy(asc(schema.comments.externalCreatedAt)).limit(40);
    transcript = cs.filter((c) => !c.isDeleted).map((c) => ({ who: c.direction === "inbound" ? "customer" : "brand", text: c.body }));
  } else if (conv.kind === "review") {
    const r = await ctx.db.query.reviews.findFirst({ where: eq(schema.reviews.conversationId, conv.id) });
    if (r) transcript = [{ who: "customer", text: `${r.rating}★ review: ${r.body ?? "(no text)"}` }, ...(r.replyBody ? [{ who: "brand" as const, text: r.replyBody }] : [])];
  } else {
    const ms = await ctx.db.select().from(schema.messages).where(eq(schema.messages.conversationId, conv.id)).orderBy(desc(schema.messages.createdAt)).limit(30);
    transcript = ms.reverse().map((m) => ({ who: m.direction === "in" ? "customer" : m.direction === "note" ? "note" : "brand", text: m.body }));
  }
  const deal = contact ? await ctx.db.query.deals.findFirst({ where: and(eq(schema.deals.contactId, contact.id), isNull(schema.deals.wonAt), isNull(schema.deals.lostAt)) }) : null;
  const lastCustomer = [...transcript].reverse().find((t) => t.who === "customer")?.text ?? "";
  return { conv, contact, obj, transcript, deal, lastCustomer };
}

function languageInstruction(ctx: Ctx, detected: string) {
  const mode = ctx.workspace.settings?.social?.ai?.languageMode ?? "match";
  if (mode === "bangla") return "Reply in Bangla script.";
  if (mode === "english") return "Reply in English.";
  if (detected === "bn") return "Reply in Bangla script (natural Bangladeshi usage).";
  if (detected === "banglish") return (ctx.workspace.settings?.social?.ai?.banglishReply ?? "banglish") === "banglish" ? "The customer wrote Banglish (Bangla in Latin letters) — reply in the same Banglish style." : "The customer wrote Banglish — reply in Bangla script.";
  return "Reply in English.";
}

/** Strip personal data from public replies (guardrail). */
export function scrubPublic(text: string) {
  let t = text;
  for (const p of extractPhones(text)) t = t.split(p).join("[number shared privately]");
  for (const e of extractEmails(text)) t = t.split(e).join("[email shared privately]");
  return t.replace(/(\+?880|0)1[3-9]\d{2}[\s-]?\d{6}/g, "[number shared privately]");
}

/** Claims of price / discount must appear in the KB answers used (guardrail). */
function unsupportedMoney(text: string, grounding: string) {
  const nums = text.match(/(\d[\d,.]*\s?(?:lakh|lac|crore|লাখ|কোটি|%|tk|taka|৳)?)/gi) ?? [];
  return MONEY.test(text) && nums.some((n) => /\d{2,}/.test(n) && !grounding.includes(n.replace(/\s/g, "").replace(/(lakh|lac|crore|tk|taka|৳|%)$/i, "")));
}

/* ---------------- suggestions (SOC-AI-002/003/004) ---------------- */

export async function suggestReplies(ctx: Ctx, conversationId: string, opts: { mode?: "public" | "private" } = {}): Promise<{ suggestions: Suggestion[]; classification: Classification; knowledge: { id: string; question: string }[]; source: "ai" | "knowledge" }> {
  const t = await threadContext(ctx, conversationId);
  const cls = classify(t.lastCustomer || t.transcript.map((x) => x.text).join(" "));
  const isPublic = (opts.mode ?? (t.conv.kind === "dm" ? "private" : "public")) === "public";
  const risky = RISKY_INTENTS.includes(cls.intent ?? "") || LEGAL.test(t.lastCustomer);
  const kb = await retrieveKnowledge(ctx, `${t.lastCustomer} ${t.obj?.captionExcerpt ?? ""}`, { accountId: t.conv.socialAccountId, scope: t.contact?.project ?? t.obj?.campaignName });
  const grounding = kb.map((k) => `Q: ${k.entry.question}\nA: ${k.entry.answer}`).join("\n\n");
  const name = t.contact?.firstName ?? "";

  if (!aiConfigured()) {
    // deterministic fallback: knowledge answers + safe templates
    const lang = detectLanguage(t.lastCustomer);
    const out: Suggestion[] = kb.slice(0, 2).map((k) => ({ text: isPublic && MONEY.test(k.entry.answer) ? `Thanks ${name}! We've sent you the details in a private message 📩` : k.entry.answer, confidence: Math.min(0.9, 0.5 + k.score / 2), language: lang, grounded: [k.entry.id], publicSafe: !risky }));
    out.push(risky
      ? { text: lang === "bn" ? "আপনার অভিযোগটি আমরা গুরুত্ব সহকারে দেখছি। অনুগ্রহ করে ইনবক্সে বিস্তারিত জানান, আমাদের টিম দ্রুত যোগাযোগ করবে।" : `We're sorry to hear this${name ? `, ${name}` : ""}. Please send us a private message with the details and our team will get back to you right away.`, confidence: 0.6, language: lang, grounded: [], publicSafe: true, reason: "Complaint — take it private" }
      : { text: lang === "bn" ? "ধন্যবাদ! বিস্তারিত জানতে ইনবক্সে মেসেজ দিন অথবা আমাদের WhatsApp-এ যোগাযোগ করুন।" : `Thanks for your interest${name ? `, ${name}` : ""}! We've sent you the details in a private message 📩`, confidence: 0.55, language: lang, grounded: [], publicSafe: true });
    return { suggestions: out.slice(0, 3), classification: cls, knowledge: kb.map((k) => ({ id: k.entry.id, question: k.entry.question })), source: "knowledge" };
  }

  const kit = await ctx.db.query.brandKits.findFirst({ where: eq(schema.brandKits.workspaceId, ctx.workspace.id) });
  const voice = ctx.workspace.settings?.brandVoice || kit?.voice || "Warm, helpful, concise. Bangladeshi audience.";
  const system = [
    `You draft ${isPublic ? "PUBLIC comment replies (visible to everyone)" : "private message replies"} for ${ctx.workspace.name}, a ${industryOf(ctx.workspace.settings).business}. Brand voice: ${voice}.`,
    ...(industryOf(ctx.workspace.settings).compliance ? [`Industry compliance (mandatory): ${industryOf(ctx.workspace.settings).compliance}`] : []),
    languageInstruction(ctx, cls.language),
    "Rules you must follow:",
    "- Only state facts (prices, discounts, availability, dates, locations) that appear in the KNOWLEDGE section. If the answer is not there, offer to share details privately or have an agent follow up.",
    isPublic ? "- This is public: never include phone numbers, emails, addresses of the customer or any personal data. Never quote prices publicly unless the knowledge says prices may be shared publicly; instead invite them to DM/WhatsApp." : "- Keep it under 80 words.",
    "- If the customer complains, threatens legal action or is angry: apologise briefly and move the conversation to private. Do not argue or admit liability.",
    "- Keep public replies under 40 words. Vary wording between suggestions.",
    'Respond with JSON only: {"suggestions":[{"text":"…","confidence":0-1,"grounded":["knowledge ids used"],"reason":"short why"}]} with 2 or 3 suggestions.',
  ].join("\n");
  const user = [
    t.obj ? `POST/AD: ${t.obj.type}${t.obj.campaignName ? ` · campaign "${t.obj.campaignName}"` : ""}: ${t.obj.captionExcerpt ?? ""}` : "",
    `CUSTOMER: ${t.contact ? fullName(t.contact) : "unknown"}${t.contact?.project ? ` · interested in ${t.contact.project}` : ""}${t.deal ? ` · open deal` : ""}`,
    `CLASSIFICATION: intent=${cls.intent} sentiment=${cls.sentiment} language=${cls.language}`,
    `KNOWLEDGE:\n${grounding || "(none matched)"}${kb.length ? `\nIDs: ${kb.map((k) => k.entry.id).join(", ")}` : ""}`,
    `THREAD:\n${t.transcript.slice(-15).map((x) => `${x.who}: ${x.text}`).join("\n")}`,
  ].filter(Boolean).join("\n\n");
  const { text } = await complete(ctx, { feature: "social_suggest", tier: "fast", system, messages: [{ role: "user", content: user }], maxTokens: 900, cache: false });
  const parsed = parseJson<{ suggestions: { text: string; confidence: number; grounded?: string[]; reason?: string }[] }>(text);
  const raw = parsed?.suggestions?.length ? parsed.suggestions : [{ text: text.trim(), confidence: 0.4 }];
  const suggestions: Suggestion[] = raw.slice(0, 3).map((s) => {
    let body = isPublic ? scrubPublic(s.text) : s.text;
    let confidence = Math.max(0, Math.min(1, Number(s.confidence) || 0.5));
    let reason = s.reason;
    if (unsupportedMoney(body, grounding)) { confidence = Math.min(confidence, 0.3); reason = "Mentions a price/discount not found in the knowledge base — check before sending"; }
    if (risky && isPublic) confidence = Math.min(confidence, 0.4);
    if (body.length > (isPublic ? 600 : 1500)) body = body.slice(0, isPublic ? 600 : 1500);
    return { text: body.trim(), confidence, language: detectLanguage(body), grounded: (s.grounded ?? []).filter((g) => kb.some((k) => k.entry.id === g)), publicSafe: !(risky && isPublic), reason };
  });
  return { suggestions, classification: cls, knowledge: kb.map((k) => ({ id: k.entry.id, question: k.entry.question })), source: "ai" };
}

/* ---------------- autopilot (SOC-AI-005/006) ---------------- */

export async function autopilotReply(ctx: Ctx, e: RuleEvent, by: By): Promise<string> {
  const ai = ctx.workspace.settings?.social?.ai ?? {};
  const threshold = ai.threshold ?? 0.8;
  const isComment = !!e.comment;
  const { suggestions, classification } = await suggestReplies(ctx, e.conversation.id, { mode: isComment ? "public" : "private" });
  const best = suggestions.sort((a, b) => b.confidence - a.confidence)[0];
  if (!best?.text) return "no suggestion";
  const intentOk = !ai.allowedIntents?.length || ai.allowedIntents.includes(classification.intent ?? "");
  const risky = RISKY_INTENTS.includes(classification.intent ?? "") || LEGAL.test(e.text);
  const publicOk = !isComment || ai.publicReplies !== false;
  // regulated categories (banking, healthcare, pharma) never auto-send public replies, whatever the settings say
  const regulatedPublic = industryOf(ctx.workspace.settings).regulated && isComment;
  const auto = !!ai.autopilot && intentOk && !risky && publicOk && !regulatedPublic && best.confidence >= threshold && best.publicSafe;
  const svc = await import("@/lib/services/social");
  if (auto) {
    const aiBy: By = { type: "ai", name: `Social AI (${by.name ?? "autopilot"})` };
    if (e.comment) await svc.replyToComment(ctx, e.comment.id, best.text, aiBy);
    else if (e.review) await svc.replyToReview(ctx, e.review.id, best.text, aiBy);
    else {
      const { sendMessage } = await import("@/lib/services/messaging");
      await sendMessage(ctx, { contactId: e.contactId, channel: e.conversation.channel, body: best.text, conversationId: e.conversation.id, source: "ai" });
    }
    return `AI replied (confidence ${best.confidence.toFixed(2)})`;
  }
  const { proposeAction } = await import("./features");
  await proposeAction(ctx, {
    agent: "social_ai", kind: "social_reply",
    proposedAction: { conversationId: e.conversation.id, commentId: e.comment?.id ?? null, reviewId: e.review?.id ?? null, text: best.text, confidence: best.confidence, alternatives: suggestions.slice(1).map((s) => s.text) },
    reasoning: risky ? "Complaint or legal language — needs a human check" : best.confidence < threshold ? `Confidence ${best.confidence.toFixed(2)} below threshold ${threshold}` : !ai.autopilot ? "Autopilot is off — review AI draft" : !intentOk ? `Intent "${classification.intent}" not enabled for autopilot` : best.reason ?? "Review before sending",
    expectedImpact: "Faster first response",
  });
  return "AI draft sent to approval queue";
}

/** SOC-AI-008: draft a Google review reply for approval (always human-approved). */
export async function draftReviewReply(ctx: Ctx, reviewId: string) {
  const rev = await ctx.db.query.reviews.findFirst({ where: and(eq(schema.reviews.id, reviewId), eq(schema.reviews.workspaceId, ctx.workspace.id)) });
  if (!rev || rev.replyStatus === "published") return null;
  const { suggestions } = await suggestReplies(ctx, rev.conversationId, { mode: "public" });
  const best = suggestions[0];
  if (!best) return null;
  await ctx.db.update(schema.reviews).set({ replyBody: best.text, replyStatus: "pending_approval", updatedAt: new Date() }).where(eq(schema.reviews.id, rev.id));
  const { proposeAction } = await import("./features");
  await proposeAction(ctx, { agent: "social_ai", kind: "social_reply", proposedAction: { conversationId: rev.conversationId, reviewId: rev.id, text: best.text, confidence: best.confidence }, reasoning: `${rev.rating}★ review — AI drafted a reply`, expectedImpact: "Protects local reputation" });
  return best;
}

/** Executes an approved social_reply (called from the AI approval queue). */
export async function executeSocialReply(ctx: Ctx, p: { conversationId: string; commentId?: string | null; reviewId?: string | null; text: string }) {
  const svc = await import("@/lib/services/social");
  const by: By = { type: "ai", name: "Social AI (approved)" };
  if (p.reviewId) return svc.replyToReview(ctx, p.reviewId, p.text, by);
  if (p.commentId) return svc.replyToComment(ctx, p.commentId, p.text, by);
  const conv = await ctx.db.query.conversations.findFirst({ where: eq(schema.conversations.id, p.conversationId) });
  if (!conv) throw new Error("Conversation not found");
  const { sendMessage } = await import("@/lib/services/messaging");
  return sendMessage(ctx, { contactId: conv.contactId, channel: conv.channel, body: p.text, conversationId: conv.id, source: "ai" });
}

/** SOC-AI-007: summary note on resolve (comment threads and reviews included). */
export async function summarizeSocialConversation(ctx: Ctx, conversationId: string) {
  const t = await threadContext(ctx, conversationId);
  if (t.transcript.length < 2) return null;
  if (t.conv.kind === "dm") {
    const { summarizeConversation } = await import("./features");
    return summarizeConversation(ctx, conversationId);
  }
  if (!aiConfigured()) return null;
  const { text } = await complete(ctx, { feature: "summarize", tier: "fast", maxTokens: 400, system: "Summarize this social media thread for a CRM note in 2 sentences. Plain text.", messages: [{ role: "user", content: t.transcript.map((x) => `${x.who}: ${x.text}`).join("\n").slice(0, 12000) }] });
  await ctx.db.insert(schema.messages).values({ workspaceId: ctx.workspace.id, conversationId, direction: "note", channel: t.conv.channel, body: `🧠 AI summary: ${text.trim()}`, status: "sent" });
  return { summary: text.trim() };
}
