import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError } from '../../lib/errors';
import { FIELD_LABEL, fullName, phoneKeyOf, updateContact } from './crm-contacts.service';
import { ROLE, clip, obj, run, str } from './crm-ai.service';
import type { Actor } from './crm-users.service';

/**
 * AI clean-up suggestions (C6): likely duplicates, and tidier phone numbers,
 * city and state names, company spellings and name capitals.
 *
 * The AI only proposes. The server keeps a suggestion only if it is a tidy-up
 * of what is there — a phone keeps its digits, a name only changes case and
 * spacing, a city or company changes a few letters, a state becomes a real
 * Indian state — and applying one re-checks that the field still holds what
 * the suggestion was made from. Exact duplicates (same email or phone) are
 * found without AI.
 */

export const CLEANUP_FIELDS = ['firstName', 'lastName', 'designation', 'companyName', 'city', 'state', 'phone'] as const;
export type CleanupField = (typeof CLEANUP_FIELDS)[number];

const SAMPLE = 150;

const STATES = [
  'Andhra Pradesh', 'Arunachal Pradesh', 'Assam', 'Bihar', 'Chhattisgarh', 'Goa', 'Gujarat', 'Haryana', 'Himachal Pradesh', 'Jharkhand', 'Karnataka', 'Kerala',
  'Madhya Pradesh', 'Maharashtra', 'Manipur', 'Meghalaya', 'Mizoram', 'Nagaland', 'Odisha', 'Punjab', 'Rajasthan', 'Sikkim', 'Tamil Nadu', 'Telangana', 'Tripura',
  'Uttar Pradesh', 'Uttarakhand', 'West Bengal', 'Andaman and Nicobar Islands', 'Chandigarh', 'Dadra and Nagar Haveli and Daman and Diu', 'Delhi',
  'Jammu and Kashmir', 'Ladakh', 'Lakshadweep', 'Puducherry',
];

const letters = (s: string) => s.toLowerCase().replace(/[^a-z0-9]/g, '');

function distance(a: string, b: string) {
  const dp = Array.from({ length: b.length + 1 }, (_, j) => j);
  for (let i = 1; i <= a.length; i++) {
    let prev = dp[0];
    dp[0] = i;
    for (let j = 1; j <= b.length; j++) {
      const tmp = dp[j];
      dp[j] = Math.min(dp[j] + 1, dp[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
      prev = tmp;
    }
  }
  return dp[b.length];
}

/** The same number written differently: only a leading 0 or +91 may differ. */
function samePhone(a: string, b: string) {
  const prefixOk = (d: string) => d.length <= 10 || ['0', '91', '091', '0091'].includes(d.slice(0, d.length - 10));
  const da = a.replace(/\D/g, '');
  const db = b.replace(/\D/g, '');
  return da.slice(-10) === db.slice(-10) && Math.min(da.length, db.length) >= Math.min(10, Math.max(da.length, db.length)) && prefixOk(da) && prefixOk(db);
}

/** Is `to` a tidy-up of `from` for this field? */
export function isTidyFix(field: CleanupField, from: string | null, to: string | null): boolean {
  if (!from?.trim() || !to?.trim() || from === to || to.length > 160) return false;
  const a = letters(from);
  const b = letters(to);
  switch (field) {
    case 'phone':
      return /^[0-9+()\-\s.]{7,20}$/.test(to) && phoneKeyOf(to) === phoneKeyOf(from) && samePhone(from, to);
    case 'firstName':
    case 'lastName':
    case 'designation':
      return a === b;
    case 'state':
      return STATES.includes(to);
    case 'city':
      return !!b && distance(a, b) <= Math.max(2, Math.ceil(Math.max(a.length, b.length) * 0.5));
    case 'companyName':
      return !!b && distance(a, b) <= Math.max(2, Math.ceil(Math.max(a.length, b.length) * 0.35));
  }
}

type Brief = { id: string; firstName: string; lastName: string | null; companyName: string | null; email: string | null; phone: string | null; city: string | null };
const brief = (c: Brief) => ({ id: c.id, name: fullName(c), companyName: c.companyName, email: c.email, phone: c.phone, city: c.city });

export async function cleanupSuggestions(actor: Actor) {
  const sel = { id: true, firstName: true, lastName: true, designation: true, companyName: true, city: true, state: true, phone: true, email: true, emailKey: true, phoneKey: true } as const;
  const [contacts, emailDupes, phoneDupes, cities] = await Promise.all([
    prismaUnscoped.crmContact.findMany({ where: { deletedAt: null }, orderBy: { updatedAt: 'desc' }, take: SAMPLE, select: sel }),
    prismaUnscoped.$queryRaw<{ key: string }[]>`SELECT "emailKey" AS key FROM "CrmContact" WHERE "deletedAt" IS NULL AND "emailKey" IS NOT NULL GROUP BY "emailKey" HAVING count(*) > 1 LIMIT 20`,
    prismaUnscoped.$queryRaw<{ key: string }[]>`SELECT "phoneKey" AS key FROM "CrmContact" WHERE "deletedAt" IS NULL AND "phoneKey" IS NOT NULL GROUP BY "phoneKey" HAVING count(*) > 1 LIMIT 20`,
    prismaUnscoped.$queryRaw<{ city: string; n: bigint }[]>`SELECT city, count(*) AS n FROM "CrmContact" WHERE "deletedAt" IS NULL AND city IS NOT NULL GROUP BY city ORDER BY n DESC LIMIT 60`,
  ]);

  // Exact duplicates first: the same email or the same phone.
  const exact: { contacts: ReturnType<typeof brief>[]; reason: string; exact: true }[] = [];
  const seen = new Set<string>();
  for (const [rows, field, why] of [[emailDupes, 'emailKey', 'Same email'], [phoneDupes, 'phoneKey', 'Same phone number']] as const) {
    for (const { key } of rows) {
      const group = await prismaUnscoped.crmContact.findMany({ where: { deletedAt: null, [field]: key }, orderBy: { createdAt: 'asc' }, take: 5, select: sel });
      const sig = group.map((g) => g.id).sort().join(',');
      if (group.length < 2 || seen.has(sig)) continue;
      seen.add(sig);
      exact.push({ contacts: group.map(brief), reason: why, exact: true });
    }
  }

  if (!contacts.length) return { fixes: [], duplicates: exact, checked: 0 };
  const refs = new Map(contacts.map((c, i) => [`c${i + 1}`, c]));
  const r = await run<{ fixes: { ref: string; field: string; to: string; reason: string }[]; duplicates: { refs: string[]; reason: string }[] }>('cleanup', actor, {
    name: 'crm_cleanup',
    system: `${ROLE}
You tidy a CRM's contacts. Suggest fixes only where a value is clearly messy:
- phone: Indian mobiles as "+91 98765 43210" (keep every digit; landlines keep their STD code); never change digits.
- firstName, lastName, designation: fix capitals and spacing only ("amit" → "Amit", "chief  warden" → "Chief Warden").
- city: fix misspellings and capitals, preferring the spelling most used in this CRM (city counts below).
- state: the full official name of an Indian state or union territory ("MP" → "Madhya Pradesh").
- companyName: fix obvious misspellings and capitals of the same company used elsewhere in the list.
Do not change correct values, invent missing ones, or translate. At most 40 fixes, each with a short reason.
Then list likely duplicates: contacts that are probably the same person (same name with the same company or city, or the same name with a near-identical phone). At most 15 groups, each with a short reason.
City counts in the CRM: ${cities.map((c) => `${c.city} (${Number(c.n)})`).join(', ') || 'none'}.`,
    user: `<data>${JSON.stringify(contacts.map((c, i) => ({ ref: `c${i + 1}`, firstName: c.firstName, lastName: c.lastName, designation: c.designation, companyName: c.companyName, city: c.city, state: c.state, phone: c.phone })))}</data>`,
    maxTokens: 4000,
    schema: obj({
      fixes: { type: 'array', items: obj({ ref: str, field: { type: 'string', enum: [...CLEANUP_FIELDS] }, to: str, reason: str }) },
      duplicates: { type: 'array', items: obj({ refs: { type: 'array', items: str }, reason: str }) },
    }),
  });

  const fixes: { contactId: string; name: string; field: CleanupField; label: string; from: string; to: string; reason: string }[] = [];
  for (const f of r.fixes) {
    const c = refs.get(f.ref.trim().toLowerCase());
    const field = f.field as CleanupField;
    if (!c || !CLEANUP_FIELDS.includes(field)) continue;
    const from = c[field];
    const to = f.to.trim().replace(/\s+/g, ' ');
    if (!isTidyFix(field, from, to) || fixes.some((x) => x.contactId === c.id && x.field === field)) continue;
    fixes.push({ contactId: c.id, name: fullName(c), field, label: FIELD_LABEL[field], from: from!, to, reason: clip(f.reason, 160) });
    if (fixes.length >= 40) break;
  }
  const duplicates: { contacts: ReturnType<typeof brief>[]; reason: string; exact: boolean }[] = [...exact];
  for (const d of r.duplicates) {
    const group = [...new Set(d.refs.map((x) => x.trim().toLowerCase()))].map((x) => refs.get(x)).filter((c): c is (typeof contacts)[number] => !!c);
    const sig = group.map((g) => g.id).sort().join(',');
    if (group.length < 2 || seen.has(sig)) continue;
    seen.add(sig);
    duplicates.push({ contacts: group.slice(0, 5).map(brief), reason: clip(d.reason, 160), exact: false });
    if (duplicates.length >= 25) break;
  }
  return { fixes, duplicates, checked: contacts.length };
}

/** Apply the fixes a person ticked, each only if the field has not moved on. */
export async function applyCleanup(fixes: { contactId: string; field: CleanupField; from: string; to: string }[], actor: Actor) {
  if (!fixes.length) throw new BadRequestError('Pick at least one fix.');
  const byContact = new Map<string, typeof fixes>();
  for (const f of fixes) byContact.set(f.contactId, [...(byContact.get(f.contactId) ?? []), f]);
  let applied = 0;
  let skipped = 0;
  for (const [id, list] of byContact) {
    const c = await prismaUnscoped.crmContact.findFirst({ where: { id, deletedAt: null }, select: { firstName: true, lastName: true, designation: true, companyName: true, city: true, state: true, phone: true } });
    const input: Partial<Record<CleanupField, string>> = {};
    for (const f of list) {
      if (c && c[f.field] === f.from && isTidyFix(f.field, f.from, f.to) && input[f.field] === undefined) input[f.field] = f.to;
      else skipped++;
    }
    const n = Object.keys(input).length;
    if (!n) continue;
    await updateContact(id, input, actor);
    applied += n;
  }
  return { applied, skipped };
}
