/**
 * Rule-based text understanding for comments, DMs and reviews (SOC-040, SOC-042, SOC-060).
 * Works in English, Bangla script and Banglish (Bangla in Latin letters). AI classification (SOC-AI-001)
 * refines these results when an AI key is configured; these rules always run first and never need a network call.
 */
import { normalizeEmail, normalizePhone } from "@/lib/util";

export type Classification = {
  intent: string | null; // price_inquiry | location_inquiry | booking | interested | complaint | support | spam | thanks | null
  sentiment: "positive" | "neutral" | "negative";
  language: "en" | "bn" | "banglish";
  phones: string[];
  emails: string[];
  hasLink: boolean;
  profanity: boolean;
  spam: boolean;
  toxicity: number; // 0..1
  urgency: "low" | "normal" | "high";
  leadIntent: boolean;
};

const BN_DIGITS = /[০-৯]/g;
export const toLatinDigits = (s: string) => s.replace(BN_DIGITS, (d) => String(d.charCodeAt(0) - 0x09e6));

const BANGLISH = /\b(koto|kot[oa]|dam|daam|ache|achhe|kothay|kothai|bhai|vai|apu|kemon|chai|lagbe|janaben|jante|bolben|plz|pls|kivabe|kobe|ki\b|na\b|hobe|nibo|kinte|flat er|taka|tk\b)/i;
const BANGLA_SCRIPT = /[ঀ-৿]/;

const INTENTS: [string, RegExp][] = [
  ["complaint", /\b(complain|complaint|fraud|scam|cheat|cheater|worst|refund|legal|lawyer|court|police|fake|liar|never again)\b|বাটপার|প্রতারণা|প্রতারক|ভুয়া|অভিযোগ|মামলা|ধোঁকা|batpar|vua|bhua|protarok|abhijog/i],
  ["price_inquiry", /\b(price|prize|pricing|rate|cost|how much|per sft|per sqft|dam|daam|koto|kot[oa])\b|দাম|কত|মূল্য|রেট|খরচ/i],
  ["location_inquiry", /\b(location|where|address|map|kothay|kothai|kon jaygay|kon area)\b|কোথায়|ঠিকানা|লোকেশন|কোন এলাকা/i],
  ["booking", /\b(book|booking|site visit|visit|appointment|schedule|meet|dekhte|dekha)\b|বুকিং|ভিজিট|দেখতে চাই|সাক্ষাৎ/i],
  ["interested", /\b(interested|interest|details|detail|info|information|inbox|dm me|send me|more info|brochure|janaben|jante chai|jante)\b|জানতে চাই|বিস্তারিত|আগ্রহী|ইন্টারেস্টেড|ইনবক্স/i],
  ["support", /\b(help|problem|issue|not working|support|delay|handover|when will)\b|সমস্যা|সাহায্য|কবে/i],
  ["thanks", /\b(thanks|thank you|thx|great|awesome|nice|beautiful|love)\b|ধন্যবাদ|সুন্দর|দারুণ|চমৎকার/i],
];
export const LEAD_INTENTS = ["price_inquiry", "location_inquiry", "booking", "interested"];

const POSITIVE = /\b(good|great|awesome|nice|love|beautiful|excellent|amazing|best|happy|thanks|thank you|wow|perfect)\b|ভালো|সুন্দর|দারুণ|চমৎকার|ধন্যবাদ|অসাধারণ|valo|bhalo|sundor|darun/i;
const NEGATIVE = /\b(bad|worst|poor|terrible|hate|angry|disappointed|fraud|scam|cheat|delay|late|never|useless|horrible|awful)\b|খারাপ|বাজে|ভুয়া|প্রতারণা|বাটপার|দেরি|kharap|baje|faltu/i;

/** Default profanity lists (English + Bangla + Banglish). Workspaces extend these in Settings → Social. */
export const DEFAULT_PROFANITY = [
  "fuck", "f*ck", "shit", "bitch", "bastard", "asshole", "dick", "slut", "whore", "motherfucker",
  "শালা", "হারামি", "হারামজাদা", "কুত্তা", "শুয়োর", "বাল", "চুদ", "মাগি", "খানকি",
  "shala", "harami", "haramjada", "kutta", "shuor", "bal\\b", "chod", "magi", "khanki", "bokachoda",
];

const SPAM = /\b(?:earn \$|crypto|bitcoin|forex|investment plan|follow back|f4f|check my (?:profile|page)|whatsapp me for loan|click here|free followers|onlyfans|telegram channel)\b|([^\s.!?])\1{7,}/i;
const LINK = /(https?:\/\/|www\.|\b[a-z0-9-]+\.(com|net|org|xyz|io|me|bd|info|link|ly)\b)/i;

/** Bangladesh-first phone extraction (01XXXXXXXXX, +8801…, 8801…, Bangla digits ০১৭…, spaced/dashed) plus generic international numbers. */
export function extractPhones(text: string, defaultCountry = "880"): string[] {
  const t = toLatinDigits(text);
  const out = new Set<string>();
  const re = /(?:\+?\s?8\s?8\s?)?0\s?1[3-9](?:[\s.-]?\d){8}|\+\d(?:[\s.-]?\d){9,14}/g;
  for (const m of t.match(re) ?? []) {
    const n = normalizePhone(m.replace(/[\s.-]/g, ""), defaultCountry);
    if (n) out.add(n);
  }
  return [...out];
}

export function extractEmails(text: string): string[] {
  return [...new Set((text.match(/[^\s@<>()"',;]+@[^\s@<>()"',;]+\.[a-z]{2,}/gi) ?? []).map((e) => normalizeEmail(e)).filter(Boolean) as string[])];
}

export function detectLanguage(text: string): Classification["language"] {
  if (BANGLA_SCRIPT.test(text)) return "bn";
  if (BANGLISH.test(text)) return "banglish";
  return "en";
}

export function containsWord(text: string, words: string[]) {
  const t = text.toLowerCase();
  return words.some((w) => {
    const raw = w.toLowerCase().trim();
    if (!raw) return false;
    if (BANGLA_SCRIPT.test(raw)) return t.includes(raw);
    // a trailing "\b" in a list entry means "whole word only" (e.g. "bal\b" must not match "balance")
    const whole = raw.endsWith("\\b");
    const word = (whole ? raw.slice(0, -2) : raw).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
    return new RegExp(`(^|[^a-z0-9])${word}${whole ? "(?![a-z0-9])" : ""}`, "i").test(t);
  });
}

export function classify(text: string, opts: { defaultCountry?: string; extraProfanity?: string[] } = {}): Classification {
  const body = text ?? "";
  const phones = extractPhones(body, opts.defaultCountry);
  const emails = extractEmails(body);
  const profanity = containsWord(body, [...DEFAULT_PROFANITY, ...(opts.extraProfanity ?? [])]);
  const hasLink = LINK.test(body);
  const spam = SPAM.test(body) || (hasLink && /\b(earn|free|win|offer|promo)\b/i.test(body));
  let intent: string | null = spam ? "spam" : null;
  if (!intent) for (const [name, re] of INTENTS) if (re.test(body)) { intent = name; break; }
  if (!intent && (phones.length || emails.length)) intent = "interested";
  const neg = NEGATIVE.test(body) || intent === "complaint" || profanity;
  const pos = POSITIVE.test(body);
  const sentiment = neg && !pos ? "negative" : neg && pos ? (intent === "complaint" ? "negative" : "neutral") : pos ? "positive" : "neutral";
  const toxicity = profanity ? 0.9 : intent === "complaint" ? 0.4 : 0;
  const urgency = intent === "complaint" || /\b(urgent|asap|immediately|today)\b|জরুরি|এখনই/i.test(body) ? "high" : LEAD_INTENTS.includes(intent ?? "") ? "normal" : "low";
  return { intent, sentiment, language: detectLanguage(body), phones, emails, hasLink, profanity, spam, toxicity, urgency, leadIntent: LEAD_INTENTS.includes(intent ?? "") || phones.length > 0 };
}
