import { CrmStageKind, Prisma } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { BadRequestError, NotFoundError } from '../../lib/errors';
import { crmEmail, type CrmEmailItem } from '../../lib/email-templates';
import { superAdminCopyAddress } from './crm-settings.service';
import { crmMembersWithPrefs, crmUrl, deliver, ist, istDayStart, rupees } from './crm-mail';
import { PROPERTY_TYPE_LABEL, STATUS_LABEL } from './crm-contacts.service';
import { ROLE, aiBlocked, assertAiAvailable, clip, obj, run, runWithModel, str, today } from './crm-ai.service';
import type { Actor } from './crm-users.service';

/**
 * Better marketing with AI (C6): the marketing insights report and campaign
 * ideas for a list.
 *
 * Insights: the figures — which sources, cities, states, property types and
 * bed sizes win, and where open deals stall — are counted from the CRM, then
 * the AI (the "reports" model) says what they mean and what to do next. The
 * report is saved, made on demand or automatically for the past month on the
 * 1st, and the monthly one is emailed to the team.
 *
 * Campaigns: a list is described to the AI by its make-up only (counts of
 * property types, cities, statuses, roles) — no names, emails or phones — and
 * it suggests angles and writes email, WhatsApp and LinkedIn copy.
 */

const DAY = 86_400_000;
const IST_MS = 330 * 60_000;

// ── The figures ────────────────────────────────────────────────────────────

export interface InsightRow {
  key: string;
  deals: number;
  won: number;
  lost: number;
  open: number;
  winRate: number | null;
  wonValue: number;
  avgDaysToClose: number | null;
}

export interface InsightStats {
  from: string;
  to: string;
  totals: { newContacts: number; newDeals: number; won: number; lost: number; winRate: number | null; wonValue: number; avgDealSize: number | null; avgDaysToClose: number | null; openNow: number; openValue: number };
  bySource: InsightRow[];
  byCity: InsightRow[];
  byState: InsightRow[];
  byPropertyType: InsightRow[];
  byBeds: InsightRow[];
  stalls: { stage: string; open: number; avgDaysInStage: number; quiet14: number }[];
  lostReasons: { reason: string; count: number }[];
}

export interface InsightNarrative {
  headline: string;
  findings: { title: string; detail: string }[];
  stalls: string[];
  actions: string[];
}

function bedBucket(n: number | null | undefined) {
  if (n === null || n === undefined) return 'Not set';
  if (n < 50) return 'Under 50 beds';
  if (n < 150) return '50–149 beds';
  if (n < 300) return '150–299 beds';
  return '300+ beds';
}

const pct = (won: number, lost: number) => (won + lost ? Math.round((won / (won + lost)) * 100) : null);

export async function insightStats(from: Date, to: Date): Promise<InsightStats> {
  const [deals, newContacts, openNow, lastActivity] = await Promise.all([
    prismaUnscoped.crmDeal.findMany({
      where: { deletedAt: null, OR: [{ createdAt: { gte: from, lt: to } }, { wonAt: { gte: from, lt: to } }, { lostAt: { gte: from, lt: to } }] },
      select: {
        value: true, source: true, beds: true, createdAt: true, wonAt: true, lostAt: true, lostReason: true,
        stage: { select: { kind: true } },
        contact: { select: { source: true, city: true, state: true, propertyType: true, approxBeds: true } },
      },
    }),
    prismaUnscoped.crmContact.count({ where: { deletedAt: null, createdAt: { gte: from, lt: to } } }),
    prismaUnscoped.crmDeal.findMany({
      where: { deletedAt: null, stage: { kind: CrmStageKind.OPEN } },
      select: { id: true, value: true, stageChangedAt: true, updatedAt: true, stage: { select: { name: true, position: true } } },
    }),
    prismaUnscoped.crmActivity.groupBy({ by: ['dealId'], where: { dealId: { not: null } }, _max: { createdAt: true } }),
  ]);
  const inPeriod = (d: Date | null) => !!d && d >= from && d < to;
  const outcome = (d: (typeof deals)[number]) => (d.stage.kind === CrmStageKind.WON && inPeriod(d.wonAt) ? 'won' : d.stage.kind === CrmStageKind.LOST && inPeriod(d.lostAt) ? 'lost' : d.stage.kind === CrmStageKind.OPEN ? 'open' : 'other');
  const tidy = (s: string | null | undefined) => s?.trim().replace(/\s+/g, ' ') || 'Not set';
  const group = (key: (d: (typeof deals)[number]) => string, cap = 8): InsightRow[] => {
    const m = new Map<string, InsightRow & { days: number[] }>();
    // "pune" and "Pune" are one group, shown as first spelled.
    for (const d of deals) {
      const label = key(d);
      const k = label.toLowerCase();
      const r = m.get(k) ?? { key: label, deals: 0, won: 0, lost: 0, open: 0, winRate: null, wonValue: 0, avgDaysToClose: null, days: [] };
      r.deals++;
      const o = outcome(d);
      if (o === 'won') {
        r.won++;
        r.wonValue += d.value;
        r.days.push((d.wonAt!.getTime() - d.createdAt.getTime()) / DAY);
      } else if (o === 'lost') r.lost++;
      else if (o === 'open') r.open++;
      m.set(k, r);
    }
    let rows = [...m.values()].sort((a, b) => b.deals - a.deals || b.wonValue - a.wonValue);
    if (rows.length > cap) {
      const rest = rows.slice(cap - 1);
      const other = rest.reduce((o, r) => ({ ...o, deals: o.deals + r.deals, won: o.won + r.won, lost: o.lost + r.lost, open: o.open + r.open, wonValue: o.wonValue + r.wonValue, days: [...o.days, ...r.days] }), { key: 'Everything else', deals: 0, won: 0, lost: 0, open: 0, winRate: null, wonValue: 0, avgDaysToClose: null, days: [] as number[] });
      rows = [...rows.slice(0, cap - 1), other];
    }
    return rows.map(({ days, ...r }) => ({ ...r, winRate: pct(r.won, r.lost), avgDaysToClose: days.length ? Math.round(days.reduce((s, x) => s + x, 0) / days.length) : null }));
  };

  const won = deals.filter((d) => outcome(d) === 'won');
  const lost = deals.filter((d) => outcome(d) === 'lost');
  const wonValue = won.reduce((s, d) => s + d.value, 0);
  const closeDays = won.map((d) => (d.wonAt!.getTime() - d.createdAt.getTime()) / DAY);

  const lastOf = (id: string) => lastActivity.find((a) => a.dealId === id)?._max.createdAt;
  const stageMap = new Map<string, { position: number; open: number; days: number; quiet14: number }>();
  for (const d of openNow) {
    const s = stageMap.get(d.stage.name) ?? { position: d.stage.position, open: 0, days: 0, quiet14: 0 };
    s.open++;
    s.days += (to.getTime() - d.stageChangedAt.getTime()) / DAY;
    if ((lastOf(d.id) ?? d.updatedAt).getTime() < to.getTime() - 14 * DAY) s.quiet14++;
    stageMap.set(d.stage.name, s);
  }
  const reasons = new Map<string, { reason: string; count: number }>();
  for (const d of lost) {
    const r = clip(d.lostReason, 60) || 'No reason given';
    const k = r.toLowerCase();
    reasons.set(k, { reason: reasons.get(k)?.reason ?? r, count: (reasons.get(k)?.count ?? 0) + 1 });
  }

  return {
    from: from.toISOString(),
    to: to.toISOString(),
    totals: {
      newContacts,
      newDeals: deals.filter((d) => inPeriod(d.createdAt)).length,
      won: won.length,
      lost: lost.length,
      winRate: pct(won.length, lost.length),
      wonValue,
      avgDealSize: won.length ? Math.round(wonValue / won.length) : null,
      avgDaysToClose: closeDays.length ? Math.round(closeDays.reduce((s, x) => s + x, 0) / closeDays.length) : null,
      openNow: openNow.length,
      openValue: openNow.reduce((s, d) => s + d.value, 0),
    },
    bySource: group((d) => tidy(d.source ?? d.contact?.source)),
    byCity: group((d) => tidy(d.contact?.city)),
    byState: group((d) => tidy(d.contact?.state)),
    byPropertyType: group((d) => (d.contact?.propertyType ? PROPERTY_TYPE_LABEL[d.contact.propertyType] : 'Not set')),
    byBeds: group((d) => bedBucket(d.beds ?? d.contact?.approxBeds), 6),
    stalls: [...stageMap.entries()].sort((a, b) => a[1].position - b[1].position).map(([stage, s]) => ({ stage, open: s.open, avgDaysInStage: Math.round(s.days / s.open), quiet14: s.quiet14 })),
    lostReasons: [...reasons.values()].sort((a, b) => b.count - a.count).slice(0, 6),
  };
}

// ── The report ─────────────────────────────────────────────────────────────

export const INSIGHT_PERIODS = ['30d', '90d', '365d', 'lastMonth'] as const;
export type InsightPeriod = (typeof INSIGHT_PERIODS)[number];

/** First instant of the India calendar month `offset` months from now's. */
function istMonthStart(now: Date, offset = 0) {
  const s = new Date(now.getTime() + IST_MS);
  return new Date(Date.UTC(s.getUTCFullYear(), s.getUTCMonth() + offset, 1) - IST_MS);
}

const fmtDay = (d: Date) => d.toLocaleDateString('en-IN', { timeZone: 'Asia/Kolkata', day: 'numeric', month: 'short', year: 'numeric' });
const fmtMonth = (d: Date) => d.toLocaleDateString('en-IN', { timeZone: 'Asia/Kolkata', month: 'long', year: 'numeric' });

export function periodRange(period: InsightPeriod, now = new Date()) {
  if (period === 'lastMonth') {
    const from = istMonthStart(now, -1);
    return { from, to: istMonthStart(now), title: fmtMonth(from) };
  }
  const n = { '30d': 30, '90d': 90, '365d': 365 }[period];
  const to = new Date(istDayStart(now).getTime() + DAY);
  const from = new Date(to.getTime() - n * DAY);
  const label = { '30d': 'Last 30 days', '90d': 'Last 90 days', '365d': 'Last 12 months' }[period];
  return { from, to, title: `${label} (${fmtDay(from)} – ${fmtDay(new Date(to.getTime() - 1))})` };
}

const ANALYST = `You are the marketing analyst for this team. From the figures below — counted from the CRM, deals in play during the period — explain what is working and what is not.
"headline": one sentence, the most useful takeaway.
"findings": up to 5, each a short title and a 1–2 sentence detail: which sources, cities, states, property types and bed sizes win most and least (win rate = won ÷ (won + lost)), and which bring the most value. Say when a group has fewer than 5 closed deals and is too small to trust.
"stalls": up to 3 lines on where open deals get stuck (stages with long average days or many quiet deals) and why it may be happening.
"actions": up to 4 concrete marketing moves for the next month, each one line.
Use only these numbers; do not invent any. Write money in ₹ with Indian grouping.`;

async function writeNarrative(stats: InsightStats, title: string, actor: Actor | null) {
  const closed = stats.totals.won + stats.totals.lost;
  if (!stats.totals.newDeals && !closed) return { narrative: null, model: null };
  const r = await runWithModel<InsightNarrative>('insights', actor, {
    name: 'crm_insights',
    tier: 'reports',
    system: `${ROLE}\n${today()}\n${ANALYST}`,
    user: `<data>Period: ${title}\n${JSON.stringify(stats)}</data>`,
    maxTokens: 3000,
    schema: obj({ headline: str, findings: { type: 'array', items: obj({ title: str, detail: str }) }, stalls: { type: 'array', items: str }, actions: { type: 'array', items: str } }),
  });
  const n = r.data;
  return {
    model: r.model,
    narrative: {
      headline: clip(n.headline, 300),
      findings: n.findings.slice(0, 5).map((f) => ({ title: clip(f.title, 120), detail: clip(f.detail, 500) })),
      stalls: n.stalls.slice(0, 3).map((x) => clip(x, 300)),
      actions: n.actions.slice(0, 4).map((x) => clip(x, 300)),
    } satisfies InsightNarrative,
  };
}

const reportSelect = { id: true, title: true, periodFrom: true, periodTo: true, monthKey: true, createdAt: true, createdById: true } as const;

async function withNames<T extends { createdById: string | null }>(rows: T[]) {
  const ids = [...new Set(rows.map((r) => r.createdById).filter((x): x is string => !!x))];
  const people = ids.length ? await prismaUnscoped.user.findMany({ where: { id: { in: ids } }, select: { id: true, name: true } }) : [];
  return rows.map((r) => ({ ...r, createdByName: r.createdById ? people.find((p) => p.id === r.createdById)?.name ?? 'Former member' : 'Automatic (monthly)' }));
}

export async function listInsightReports() {
  return withNames(await prismaUnscoped.crmInsightReport.findMany({ orderBy: { createdAt: 'desc' }, take: 50, select: reportSelect }));
}

export async function getInsightReport(id: string) {
  const r = await prismaUnscoped.crmInsightReport.findUnique({ where: { id } });
  if (!r) throw new NotFoundError('Report not found');
  return (await withNames([r]))[0];
}

/** Make a report now. The figures are counted first; the AI only writes. */
export async function createInsightReport(period: InsightPeriod, actor: Actor | null, now = new Date(), monthKey?: string) {
  // A person hears why not; the clock just skips the month.
  if (actor) await assertAiAvailable('insights');
  else if (await aiBlocked('insights')) return null;
  const { from, to, title } = periodRange(period, now);
  const stats = await insightStats(from, to);
  const { narrative, model } = await writeNarrative(stats, title, actor);
  const r = await prismaUnscoped.crmInsightReport.create({
    data: { title, periodFrom: from, periodTo: to, monthKey: monthKey ?? null, stats: stats as unknown as Prisma.InputJsonValue, narrative: (narrative ?? Prisma.JsonNull) as Prisma.InputJsonValue, model, createdById: actor?.id ?? null },
  });
  return getInsightReport(r.id);
}

/**
 * The clock's part: on the 1st (from 09:00 India time) make last month's
 * report once and email it to everyone who keeps the weekly summary on, and
 * the super admin.
 */
export async function monthlyInsightsTick(now = new Date()) {
  const { date, hour } = ist(now);
  if (date.slice(8, 10) !== '01' || hour < 9) return 0;
  const monthKey = new Date(istMonthStart(now, -1).getTime() + IST_MS).toISOString().slice(0, 7);
  if (await prismaUnscoped.crmInsightReport.findUnique({ where: { monthKey }, select: { id: true } })) return 0;
  let report: Awaited<ReturnType<typeof createInsightReport>>;
  try {
    report = await createInsightReport('lastMonth', null, now, monthKey);
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') return 0; // another server made it
    throw e;
  }
  if (!report) return 0;
  const stats = report.stats as unknown as InsightStats;
  const n = report.narrative as unknown as InsightNarrative | null;
  const url = crmUrl(`insights/${report.id}`);
  const best = (rows: InsightRow[]) => rows.filter((r) => r.won + r.lost >= 3 && r.key !== 'Not set' && r.key !== 'Everything else').sort((a, b) => (b.winRate ?? 0) - (a.winRate ?? 0))[0];
  const bestLines: CrmEmailItem[] = (
    [
      ['Best source', best(stats.bySource)],
      ['Best city', best(stats.byCity)],
      ['Best property type', best(stats.byPropertyType)],
    ] as const
  )
    .filter(([, r]) => !!r)
    .map(([label, r]) => ({ text: `${label}: ${r!.key}`, aside: `${r!.winRate}% won · ${r!.won + r!.lost} closed` }));
  const mail = crmEmail({
    title: `Marketing insights: ${report.title}`,
    intro: n?.headline ?? 'Too few deals last month for the AI to read much into. The figures are below.',
    badge: 'Monthly insights',
    figures: [
      ['Won', `${stats.totals.won} · ${rupees(stats.totals.wonValue)}`],
      ['Win rate', stats.totals.winRate === null ? '—' : `${stats.totals.winRate}%`],
      ['New deals', String(stats.totals.newDeals)],
    ],
    sections: [
      ...(n ? [{ heading: 'What the AI sees', items: n.findings.map((f) => ({ text: f.title, sub: f.detail })) }] : []),
      { heading: 'What wins', items: bestLines, empty: 'Not enough closed deals to compare yet.' },
      ...(n?.stalls.length ? [{ heading: 'Where deals stall', items: n.stalls.map((s) => ({ text: s, tone: 'warning' as const })) }] : []),
      ...(n?.actions.length ? [{ heading: 'Try next month', items: n.actions.map((a) => ({ text: a })) }] : []),
    ],
    cta: { label: 'Open the full report', url },
    reason: 'The monthly marketing report goes to everyone who keeps the weekly summary on. Change it in your CRM profile.',
  });
  let sent = 0;
  const members = (await crmMembersWithPrefs()).filter((m) => m.prefs.weekly);
  for (const m of members) {
    const s = await deliver({ key: `insights:${monthKey}:${m.id}`, kind: 'INSIGHTS', to: m.email, userId: m.id, mail });
    if (s === 'SENT' || s === 'DRY_RUN') sent++;
  }
  const copy = await superAdminCopyAddress({ recipients: members.map((m) => m.email) });
  if (copy) {
    const s = await deliver({ key: `insights:${monthKey}:copy`, kind: 'INSIGHTS', to: copy, mail, isCopy: true });
    if (s === 'SENT' || s === 'DRY_RUN') sent++;
  }
  return sent;
}

// ── Campaign ideas and copy ────────────────────────────────────────────────

const PRODUCT = `What HostelCare does: rooms and beds, student records and documents, rent and fee collection with online payment, reminders and receipts, mess, gate passes, notices, move-outs and reports, with a mobile app. Plans are sized by properties and beds.`;

export async function campaignIdeas(listId: string, input: { goal?: string; angle?: string }, actor: Actor) {
  const list = await prismaUnscoped.crmList.findUnique({ where: { id: listId }, select: { name: true, description: true } });
  if (!list) throw new NotFoundError('List not found');
  const members = await prismaUnscoped.crmContact.findMany({
    where: { deletedAt: null, lists: { some: { listId } } },
    select: { status: true, propertyType: true, approxBeds: true, city: true, state: true, designation: true, source: true, tags: true },
    take: 5000,
  });
  if (!members.length) throw new BadRequestError('Add contacts to this list first.', 'LIST_EMPTY');
  const tally = (vals: (string | null | undefined)[], cap = 6) => {
    const m = new Map<string, number>();
    for (const v of vals) {
      const k = v?.trim();
      if (k) m.set(k, (m.get(k) ?? 0) + 1);
    }
    return [...m.entries()].sort((a, b) => b[1] - a[1]).slice(0, cap).map(([k, n]) => `${k} ${n}`).join(', ') || 'unknown';
  };
  const profile = `List "${list.name}"${list.description ? ` — ${clip(list.description, 200)}` : ''}: ${members.length} contact${members.length === 1 ? '' : 's'}.
Status: ${tally(members.map((m) => STATUS_LABEL[m.status]))}.
They run: ${tally(members.map((m) => (m.propertyType ? PROPERTY_TYPE_LABEL[m.propertyType] : null)))}.
Size: ${tally(members.map((m) => bedBucket(m.approxBeds)))}.
Cities: ${tally(members.map((m) => m.city))}. States: ${tally(members.map((m) => m.state), 4)}.
Roles: ${tally(members.map((m) => m.designation))}. Sources: ${tally(members.map((m) => m.source), 4)}. Tags: ${tally(members.flatMap((m) => m.tags), 6)}.`;
  const platform = await prismaUnscoped.platformSettings.findUnique({ where: { id: 'singleton' }, select: { platformName: true, websiteUrl: true } });
  const r = await run<{ angles: { name: string; pitch: string }[]; chosen: string; email: { subject: string; body: string }; whatsapp: string; linkedin: string }>('campaign', actor, {
    name: 'crm_campaign',
    system: `${ROLE}\n${today()}\n${PRODUCT}${platform?.websiteUrl ? ` Website: ${platform.websiteUrl}.` : ''}
Plan a campaign to this audience for ${platform?.platformName || 'HostelCare'}. Suggest 3 different angles (a short name and one sentence on why it fits this audience). ${input.angle ? 'Write the copy for the angle the marketer chose (below), and give its name as "chosen".' : 'Pick the best angle as "chosen" and write its copy.'}
Copy: an email (subject, and a body under 150 words), a WhatsApp message under 60 words, and a LinkedIn post under 120 words. Warm, plain Indian English, no markdown. {first_name} is the only placeholder you may use. Never invent prices, discounts, offers, dates, customers or features beyond what is described here. Sign the email from ${actor.name}.`,
    user: `<data>${profile}${input.goal ? `\nThe marketer's goal: ${clip(input.goal, 500)}` : ''}${input.angle ? `\nChosen angle: ${clip(input.angle, 200)}` : ''}</data>`,
    maxTokens: 2500,
    schema: obj({
      angles: { type: 'array', items: obj({ name: str, pitch: str }) },
      chosen: str,
      email: obj({ subject: str, body: str }),
      whatsapp: str,
      linkedin: str,
    }),
  });
  return {
    audience: { name: list.name, contacts: members.length },
    angles: r.angles.slice(0, 3).map((a) => ({ name: clip(a.name, 80), pitch: clip(a.pitch, 240) })),
    chosen: clip(r.chosen, 80),
    email: { subject: clip(r.email.subject, 200), body: r.email.body.trim().slice(0, 3000) },
    whatsapp: r.whatsapp.trim().slice(0, 1000),
    linkedin: r.linkedin.trim().slice(0, 3000),
  };
}
