import { demoReminders as demoRemindersTick } from './crm-demos.service';
import { retryMetaLeads } from './crm-touch.service';
import { trialJourneyTick } from './crm-trials.service';
import { nurtureTick, seasonCalls as seasonCallsTick, weeklyFunnelLines } from './crm-nurture.service';
import { createHash } from 'node:crypto';
import { CrmActivityType, CrmStageKind, Prisma } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { crmEmail, type CrmEmailItem, type CrmEmailSection } from '../../lib/email-templates';
import { getCrmSettings, superAdminCopyAddress } from './crm-settings.service';
import { crmMembersWithPrefs, crmUrl, deliver, fmtIst, fmtIstDay, fmtIstTime, ist, istAt, istDayStart, rupees, type Member } from './crm-mail';
import { flushAlerts, queueReminderCopy } from './crm-notify';
import { fullName } from './crm-contacts.service';
import { dealRef } from './crm-deals.service';
import { dailyFocus, scoreTick, topScored } from './crm-ai-scoring';
import { monthlyInsightsTick } from './crm-ai-marketing';
import { escalateLateLeads } from './crm-leads.service';

/**
 * The CRM's clock. Every few minutes `tick(now)`:
 *
 *  1. sends activity-alert batches whose ten minutes are up;
 *  2. sends next-action / follow-up reminders — the morning of the day
 *     (09:00 India time, when more than an hour away), an hour before, and
 *     an overdue nudge at 09:00 the next day if nothing changed;
 *  3. sends task reminders — an hour before, and overdue the next morning;
 *     (2) and (3) leave as one email per person per tick, and the super
 *     admin's copies as one batched email (10 Oct 2026);
 *  4. sends each member's daily summary (Mon–Sat) and Monday's weekly one at
 *     their chosen hour, and one team-wide version to the super admin.
 *
 * With AI on (C6) it first scores the open deals that are due a score, opens
 * each daily summary with the AI's "focus today", lists the best-scored deals
 * in the super admin's, and on the 1st makes and sends last month's
 * marketing report. AI trouble never stops the emails.
 *
 * Each email has a key that names the thing and the moment ("this deal's
 * 3 pm action, the hour-before reminder"), so running the tick twice — or on
 * two servers — sends nothing twice, and moving a date sends fresh ones.
 * Nothing older than three days is chased.
 */

const HOUR = 3_600_000;
const DAY = 86_400_000;
const REMIND_HOUR = 9;
const STALE = 3 * DAY;

type Window = 'morning' | 'soon' | 'overdue';

/** Which reminder, if any, is due now for something set for `at`. */
export function reminderDue(at: Date, now: Date): Window | null {
  const t = at.getTime();
  const n = now.getTime();
  if (t < n - STALE) return null;
  if (n >= t - HOUR && n < t) return 'soon';
  const atDay = ist(at).date;
  if (n < t && ist(now).date === atDay && n >= istAt(atDay, REMIND_HOUR).getTime() && t - n > HOUR) return 'morning';
  const nextMorning = istAt(atDay, REMIND_HOUR).getTime() + DAY;
  if (n >= t && n >= nextMorning) return 'overdue';
  return null;
}

const WORD: Record<Window, string> = { morning: 'Today', soon: 'In an hour', overdue: 'Overdue' };

// ── Reminders: what is due, gathered first, then sent together ─────────────

/** One reminder that is due now, and who should get it. */
interface Due {
  /** Names the thing, its time and the moment: the once-only key. */
  key: string;
  kind: 'FOLLOW_UP' | 'TASK';
  window: Window;
  at: Date;
  /** The assignee or owner — whose daily summary already lists it. */
  ownerId: string | null;
  title: string;
  text: string;
  sub: string | null;
  url: string;
  recipients: Member[];
}

async function dueFollowUps(now: Date, members: Member[], teamWide: boolean): Promise<Due[]> {
  const lo = new Date(now.getTime() - STALE - DAY);
  const hi = new Date(now.getTime() + DAY);
  const [deals, contacts] = await Promise.all([
    prismaUnscoped.crmDeal.findMany({
      where: { deletedAt: null, stage: { kind: CrmStageKind.OPEN }, nextActionAt: { gte: lo, lte: hi } },
      select: { id: true, number: true, title: true, value: true, nextStep: true, nextActionAt: true, assigneeId: true, contact: { select: { firstName: true, lastName: true, phone: true } } },
    }),
    prismaUnscoped.crmContact.findMany({
      where: { deletedAt: null, nextFollowUpAt: { gte: lo, lte: hi } },
      select: { id: true, firstName: true, lastName: true, companyName: true, phone: true, nextFollowUpAt: true, ownerId: true },
    }),
  ]);
  const items = [
    ...deals.map((d) => ({
      key: `fu:deal:${d.id}:${d.nextActionAt!.toISOString()}`,
      at: d.nextActionAt!,
      ownerId: d.assigneeId,
      title: d.nextStep ? `${d.nextStep} — ${dealRef(d.number)}` : `Next action on ${dealRef(d.number)}`,
      text: `${dealRef(d.number)} · ${d.title}`,
      sub: [d.nextStep, d.contact ? `${fullName(d.contact)}${d.contact.phone ? ` · ${d.contact.phone}` : ''}` : null, d.value ? rupees(d.value) : null].filter(Boolean).join(' · ') || null,
      url: crmUrl(`deals/${d.id}`),
    })),
    ...contacts.map((c) => ({
      key: `fu:contact:${c.id}:${c.nextFollowUpAt!.toISOString()}`,
      at: c.nextFollowUpAt!,
      ownerId: c.ownerId,
      title: `Follow up with ${fullName(c)}`,
      text: fullName(c),
      sub: [c.companyName, c.phone].filter(Boolean).join(' · ') || null,
      url: crmUrl(`contacts/${c.id}`),
    })),
  ];
  const out: Due[] = [];
  for (const it of items) {
    const w = reminderDue(it.at, now);
    if (!w) continue;
    const recipients = (teamWide ? members : members.filter((m) => m.id === it.ownerId)).filter((m) => m.prefs.followUps);
    if (recipients.length) out.push({ ...it, key: `${it.key}:${w}`, kind: 'FOLLOW_UP', window: w, recipients });
  }
  return out;
}

async function dueTasks(now: Date, members: Member[]): Promise<Due[]> {
  const tasks = await prismaUnscoped.crmTask.findMany({
    where: { done: false, dueAt: { gte: new Date(now.getTime() - STALE - DAY), lte: new Date(now.getTime() + DAY) }, assigneeId: { not: null }, OR: [{ dealId: null }, { deal: { deletedAt: null } }] },
    include: { deal: { select: { id: true, number: true, title: true } }, contact: { select: { id: true, firstName: true, lastName: true, phone: true } } },
  });
  const out: Due[] = [];
  for (const t of tasks) {
    const w = reminderDue(t.dueAt!, now);
    if (!w || w === 'morning') continue; // the daily summary lists today's tasks
    const m = members.find((x) => x.id === t.assigneeId);
    if (!m || !m.prefs.tasks) continue;
    out.push({
      key: `task:${t.id}:${t.dueAt!.toISOString()}:${w}`,
      kind: 'TASK',
      window: w,
      at: t.dueAt!,
      ownerId: t.assigneeId,
      title: t.title,
      text: t.title,
      sub: t.deal ? `${dealRef(t.deal.number)} · ${t.deal.title}` : t.contact ? `${fullName(t.contact)}${t.contact.phone ? ` · ${t.contact.phone}` : ''}` : null,
      url: t.contact ? crmUrl(`contacts/${t.contact.id}`) : t.deal ? crmUrl(`deals/${t.deal.id}`) : crmUrl('home'),
      recipients: [m],
    });
  }
  return out;
}

/** Claim a reminder for a recipient; false if it has already gone. */
async function claim(key: string) {
  try {
    await prismaUnscoped.crmReminderClaim.create({ data: { key } });
    return true;
  } catch (e) {
    if (e instanceof Prisma.PrismaClientKnownRequestError && e.code === 'P2002') return false;
    throw e;
  }
}

const TASK_WORD: Record<Window, string> = { morning: 'Today', soon: 'Due in an hour', overdue: 'Overdue' };
const wordFor = (d: Due) => (d.kind === 'TASK' ? TASK_WORD : WORD)[d.window];

/** The email for one reminder on its own — as it always looked. */
function singleReminder(d: Due, m: Member, teamWide: boolean) {
  const overdue = d.window === 'overdue';
  const thing = d.kind === 'TASK' ? 'task' : 'follow-up';
  return crmEmail({
    title: `${wordFor(d)}: ${d.title}`,
    intro: overdue
      ? `${m.name}, this ${thing} was due ${fmtIst(d.at)} and ${d.kind === 'TASK' ? 'is still open' : 'has not moved'}.`
      : d.window === 'soon'
        ? `${m.name}, this ${thing} is due at ${fmtIstTime(d.at)}.`
        : `${m.name}, this ${thing} is due today at ${fmtIstTime(d.at)}.`,
    badge: overdue ? 'Overdue' : d.kind === 'TASK' ? 'Task' : 'Reminder',
    tone: overdue ? 'warning' : 'info',
    sections: [{ heading: d.kind === 'TASK' ? 'Task' : 'Follow-up', items: [{ text: d.text, sub: d.sub, url: d.url, aside: fmtIst(d.at), tone: overdue ? 'warning' : null }] }],
    cta: { label: 'Open in the CRM', url: d.url },
    reason:
      d.kind === 'TASK'
        ? 'You get this because the task is assigned to you. Choose what you get in your CRM profile.'
        : teamWide
          ? 'Follow-up reminders go to the whole CRM team. Choose what you get in your CRM profile.'
          : 'You get this because it is yours. Choose what you get in your CRM profile.',
  });
}

/** Several reminders due at once, as one email. */
function digest(list: Due[], m: Member) {
  const overdue = list.filter((d) => d.window === 'overdue');
  const soon = list.filter((d) => d.window === 'soon');
  const today = list.filter((d) => d.window === 'morning');
  const parts = [overdue.length && `${overdue.length} overdue`, soon.length && `${soon.length} in the next hour`, today.length && `${today.length} today`].filter(Boolean).join(', ');
  const item = (d: Due): CrmEmailItem => ({
    text: d.kind === 'TASK' ? `Task: ${d.title}` : d.title,
    sub: d.kind === 'TASK' ? d.sub : d.sub ?? d.text,
    url: d.url,
    aside: d.window === 'overdue' ? `Due ${fmtIst(d.at)}` : fmtIstTime(d.at),
    tone: d.window === 'overdue' ? 'warning' : null,
  });
  const byTime = (a: Due, b: Due) => a.at.getTime() - b.at.getTime();
  return crmEmail({
    title: `${list.length} reminders: ${parts}`,
    intro: `${m.name}, everything that needs you right now, in one email.`,
    badge: overdue.length ? 'Overdue' : 'Reminders',
    tone: overdue.length ? 'warning' : 'info',
    sections: [
      ...(overdue.length ? [{ heading: 'Overdue', items: overdue.sort(byTime).map(item) }] : []),
      ...(soon.length ? [{ heading: 'In the next hour', items: soon.sort(byTime).map(item) }] : []),
      ...(today.length ? [{ heading: 'Later today', items: today.sort(byTime).map(item) }] : []),
    ],
    cta: { label: 'Open the CRM', url: crmUrl('home') },
    reason: 'Reminders due at the same time arrive together in one email. Choose what you get in your CRM profile.',
  });
}

/**
 * Send what is due: one email per person, however many of their reminders
 * fall due in this tick (one reminder keeps its own familiar email). A
 * person whose daily summary goes out today gets no separate 9 am "Today"
 * email for their own items — the summary lists them. The super admin's
 * copies join their 10-minute activity batch: one email for the whole team.
 * Each reminder is claimed per person before sending, so it goes once.
 */
async function sendReminders(now: Date, due: Due[], teamWide: boolean) {
  const { weekday } = ist(now);
  const perPerson = new Map<string, { m: Member; items: Due[] }>();
  for (const d of due) {
    for (const m of d.recipients) {
      if (d.window === 'morning' && m.id === d.ownerId && m.prefs.daily && weekday !== 0) continue;
      const g = perPerson.get(m.id) ?? { m, items: [] };
      g.items.push(d);
      perPerson.set(m.id, g);
    }
  }
  let sent = 0;
  const reached = new Map<string, { d: Due; names: string[]; emails: string[] }>();
  for (const { m, items } of perPerson.values()) {
    const mine: Due[] = [];
    for (const d of items) if (await claim(`${d.key}:${m.id}`)) mine.push(d);
    if (!mine.length) continue;
    const one = mine.length === 1;
    const id = createHash('sha1').update(mine.map((d) => d.key).sort().join('|')).digest('hex').slice(0, 16);
    const status = await deliver({
      key: one ? `${mine[0].key}:${m.id}` : `reminders:${m.id}:${id}`,
      kind: one ? mine[0].kind : 'REMINDERS',
      to: m.email,
      userId: m.id,
      mail: one ? singleReminder(mine[0], m, teamWide) : digest(mine, m),
    });
    if (status !== 'SENT' && status !== 'DRY_RUN') continue;
    sent++;
    for (const d of mine) {
      const r = reached.get(d.key) ?? { d, names: [], emails: [] };
      r.names.push(m.name);
      r.emails.push(m.email);
      reached.set(d.key, r);
    }
  }
  // The super admin's copy: a line per reminder in their activity batch,
  // skipped where they got the reminder in their own name.
  for (const { d, names, emails } of reached.values()) {
    const copy = await superAdminCopyAddress({ recipients: emails });
    if (!copy || !(await claim(`${d.key}:copy`))) continue;
    await queueReminderCopy(copy, { text: `${wordFor(d)}: ${d.title} → ${names.join(', ')}${d.window === 'overdue' ? '' : ` (${fmtIstTime(d.at)})`}`, url: d.url }, now);
  }
  return sent;
}

// ── Summaries ──────────────────────────────────────────────────────────────

/** What one person has on today: their tasks, follow-ups and deals closing soon. */
async function personalDay(m: Member, now: Date) {
  const dayStart = istDayStart(now);
  const dayEnd = new Date(dayStart.getTime() + DAY);
  const weekEnd = new Date(dayStart.getTime() + 7 * DAY);
  const [tasks, deals, contacts, closing] = await Promise.all([
    prismaUnscoped.crmTask.findMany({
      where: { assigneeId: m.id, done: false, dueAt: { lt: dayEnd }, OR: [{ dealId: null }, { deal: { deletedAt: null } }] },
      orderBy: { dueAt: 'asc' },
      take: 30,
      include: { deal: { select: { id: true, number: true } } },
    }),
    prismaUnscoped.crmDeal.findMany({ where: { assigneeId: m.id, deletedAt: null, stage: { kind: CrmStageKind.OPEN }, nextActionAt: { lt: dayEnd } }, orderBy: { nextActionAt: 'asc' }, take: 30 }),
    prismaUnscoped.crmContact.findMany({ where: { ownerId: m.id, deletedAt: null, nextFollowUpAt: { lt: dayEnd } }, orderBy: { nextFollowUpAt: 'asc' }, take: 30 }),
    prismaUnscoped.crmDeal.findMany({ where: { assigneeId: m.id, deletedAt: null, stage: { kind: CrmStageKind.OPEN }, expectedCloseDate: { gte: dayStart, lt: weekEnd } }, orderBy: { expectedCloseDate: 'asc' }, take: 20 }),
  ]);
  const late = (d: Date) => d.getTime() < dayStart.getTime();
  const due: CrmEmailItem[] = [
    ...tasks.map((t) => ({ text: t.title, sub: t.deal ? dealRef(t.deal.number) : 'Task', url: t.deal ? crmUrl(`deals/${t.deal.id}`) : null, aside: late(t.dueAt!) ? `Overdue · ${fmtIstDay(t.dueAt!)}` : fmtIstTime(t.dueAt!), tone: late(t.dueAt!) ? ('warning' as const) : null })),
    ...deals.map((d) => ({ text: d.nextStep ?? `Next action on ${dealRef(d.number)}`, sub: `${dealRef(d.number)} · ${d.title}`, url: crmUrl(`deals/${d.id}`), aside: late(d.nextActionAt!) ? `Overdue · ${fmtIstDay(d.nextActionAt!)}` : fmtIstTime(d.nextActionAt!), tone: late(d.nextActionAt!) ? ('warning' as const) : null })),
    ...contacts.map((c) => ({ text: `Follow up with ${fullName(c)}`, sub: [c.companyName, c.phone].filter(Boolean).join(' · ') || null, url: crmUrl(`contacts/${c.id}`), aside: late(c.nextFollowUpAt!) ? `Overdue · ${fmtIstDay(c.nextFollowUpAt!)}` : fmtIstTime(c.nextFollowUpAt!), tone: late(c.nextFollowUpAt!) ? ('warning' as const) : null })),
  ];
  const overdue = due.filter((d) => d.tone === 'warning').length;
  return {
    due,
    overdue,
    closing: closing.map((d) => ({ text: `${dealRef(d.number)} · ${d.title}`, url: crmUrl(`deals/${d.id}`), aside: `${rupees(d.value)} · ${fmtIstDay(d.expectedCloseDate!)}` })),
  };
}

/** What the team did between two instants, as lines and counts. */
async function teamActivity(from: Date, to: Date) {
  const acts = await prismaUnscoped.crmActivity.findMany({
    where: { createdAt: { gte: from, lt: to }, type: { in: [CrmActivityType.WON, CrmActivityType.LOST, CrmActivityType.CREATED, CrmActivityType.IMPORTED, CrmActivityType.STAGE_CHANGED, CrmActivityType.CALL, CrmActivityType.MEETING] } },
    select: { type: true, dealId: true, contactId: true, meta: true, actorName: true },
  });
  const deal = (t: CrmActivityType) => acts.filter((a) => a.type === t && a.dealId);
  const won = deal(CrmActivityType.WON);
  return {
    won,
    wonValue: won.reduce((s, a) => s + Number((a.meta as Record<string, unknown> | null)?.value ?? 0), 0),
    lost: deal(CrmActivityType.LOST),
    newDeals: acts.filter((a) => a.type === CrmActivityType.CREATED && a.dealId).length,
    newContacts: acts.filter((a) => (a.type === CrmActivityType.CREATED || a.type === CrmActivityType.IMPORTED) && a.contactId && !a.dealId).length,
    moves: deal(CrmActivityType.STAGE_CHANGED).length,
    calls: acts.filter((a) => a.type === CrmActivityType.CALL || a.type === CrmActivityType.MEETING).length,
    lines: [...won, ...deal(CrmActivityType.LOST)].map((a) => {
      const meta = (a.meta ?? {}) as Record<string, unknown>;
      return {
        text: `${a.type === CrmActivityType.WON ? 'Won' : 'Lost'}: ${String(meta.ref ?? '')} · ${String(meta.title ?? '')}`,
        sub: a.actorName ? `by ${a.actorName}` : null,
        url: a.dealId ? crmUrl(`deals/${a.dealId}`) : null,
        aside: a.type === CrmActivityType.WON && typeof meta.value === 'number' ? rupees(meta.value) : null,
        tone: a.type === CrmActivityType.WON ? ('good' as const) : null,
      };
    }),
  };
}

async function pipelineNow() {
  const open = await prismaUnscoped.crmDeal.findMany({ where: { deletedAt: null, stage: { kind: CrmStageKind.OPEN } }, select: { value: true, probability: true, stage: { select: { probability: true } } } });
  return {
    count: open.length,
    value: open.reduce((s, d) => s + d.value, 0),
    weighted: Math.round(open.reduce((s, d) => s + (d.value * (d.probability ?? d.stage.probability)) / 100, 0)),
  };
}

const inWindow = (now: Date, hour: number) => {
  const h = ist(now).hour;
  return h >= hour && h < hour + 3;
};

async function dailies(now: Date, members: Member[]) {
  const { date, weekday } = ist(now);
  if (weekday === 0) return 0; // no summaries on Sunday
  const today = istDayStart(now);
  const yesterday = await teamActivity(new Date(today.getTime() - DAY), today);
  const yLine = `${yesterday.newContacts} new contact${yesterday.newContacts === 1 ? '' : 's'}, ${yesterday.newDeals} new deal${yesterday.newDeals === 1 ? '' : 's'}, ${yesterday.moves} stage move${yesterday.moves === 1 ? '' : 's'}, ${yesterday.calls} call${yesterday.calls === 1 ? '' : 's'} or meeting${yesterday.calls === 1 ? '' : 's'}`;
  let sent = 0;
  for (const m of members.filter((x) => x.prefs.daily && inWindow(now, x.prefs.summaryHour))) {
    const key = `daily:${m.id}:${date}`;
    // Already sent: skip the work (and the AI call) the build would need.
    if (await prismaUnscoped.crmEmailLog.findUnique({ where: { key }, select: { key: true } })) continue;
    const day = await personalDay(m, now);
    const quiet = !day.due.length && !day.closing.length && !yesterday.lines.length && !yesterday.newContacts && !yesterday.newDeals;
    if (quiet) continue;
    const focus = await dailyFocus(m, now);
    const sections: CrmEmailSection[] = [
      ...(focus
        ? [{
            heading: 'Focus today (AI)',
            items: [
              ...focus.items.map((f) => ({ text: `${f.ref} · ${f.title}`, sub: f.why, url: crmUrl(`deals/${f.dealId}`), aside: f.score === null ? null : `Score ${f.score}` })),
              ...focus.risks.map((r) => ({ text: `Risk: ${r}`, tone: 'warning' as const })),
            ],
          }]
        : []),
      { heading: 'Due today', items: day.due, empty: 'Nothing due. A good day to fill the pipeline.' },
      ...(day.closing.length ? [{ heading: 'Your deals closing this week', items: day.closing }] : []),
      { heading: 'Yesterday across the team', items: yesterday.lines, empty: yLine },
    ];
    if (yesterday.lines.length) sections[sections.length - 1].items = [...yesterday.lines, { text: yLine }];
    const s = await deliver({
      key,
      kind: 'DAILY',
      to: m.email,
      userId: m.id,
      mail: crmEmail({
        title: `Your CRM day: ${day.due.length - day.overdue} due today${day.overdue ? `, ${day.overdue} overdue` : ''}`,
        intro: focus ? `Good morning ${m.name.split(' ')[0]}. Start with the ${focus.items.length === 1 ? 'deal' : `${focus.items.length} deals`} below, then what is due.` : `Good morning ${m.name.split(' ')[0]}. Here is what needs you today.`,
        badge: 'Daily summary',
        figures: [
          ['Due today', String(day.due.length - day.overdue)],
          ['Overdue', String(day.overdue)],
          ['Closing this week', String(day.closing.length)],
        ],
        sections,
        cta: { label: 'Open the CRM', url: crmUrl('home') },
        reason: 'Your daily CRM summary. Turn it off or change its time in your CRM profile.',
      }),
    });
    if (s === 'SENT' || s === 'DRY_RUN') sent++;
  }

  // One team-wide day for the super admin, instead of a copy of everyone's.
  const copy = await superAdminCopyAddress();
  if (copy && inWindow(now, REMIND_HOUR) && !(await prismaUnscoped.crmEmailLog.findUnique({ where: { key: `daily-team:${date}` }, select: { key: true } }))) {
    const rows: CrmEmailItem[] = [];
    let dueTotal = 0;
    for (const m of members) {
      const day = await personalDay(m, now);
      dueTotal += day.due.length;
      if (day.due.length || day.closing.length) rows.push({ text: m.name, sub: `${day.due.length} due today${day.overdue ? ` · ${day.overdue} overdue` : ''} · ${day.closing.length} closing this week`, tone: day.overdue ? 'warning' : null });
    }
    const pipe = await pipelineNow();
    const hot = await topScored(5);
    const s = await deliver({
      key: `daily-team:${date}`,
      kind: 'DAILY_TEAM',
      to: copy,
      isCopy: true,
      mail: crmEmail({
        title: `CRM team today: ${dueTotal} due`,
        intro: 'The whole sales team at a glance, instead of a copy of each person’s summary.',
        badge: 'Team summary',
        figures: [
          ['Open deals', String(pipe.count)],
          ['Pipeline', rupees(pipe.value)],
          ['Won yesterday', rupees(yesterday.wonValue)],
        ],
        sections: [
          ...(hot.length
            ? [{ heading: 'Best-scored open deals (AI)', items: hot.map((d) => ({ text: `${dealRef(d.number)} · ${d.title}`, sub: [d.aiScoreReason, d.assignee?.name].filter(Boolean).join(' · '), url: crmUrl(`deals/${d.id}`), aside: `Score ${d.aiScore} · ${rupees(d.value)}` })) }]
            : []),
          { heading: 'Who has what today', items: rows, empty: 'Nothing is due for anyone today.' },
          { heading: 'Yesterday', items: [...yesterday.lines, { text: yLine }] },
        ],
        cta: { label: 'Open the CRM', url: crmUrl('home') },
        reason: 'You get this because CRM emails are copied to the super admin. Change it in CRM settings.',
      }),
    });
    if (s === 'SENT' || s === 'DRY_RUN') sent++;
  }
  return sent;
}

async function weeklies(now: Date, members: Member[]) {
  const { date, weekday } = ist(now);
  if (weekday !== 1) return 0;
  const end = istDayStart(now);
  const start = new Date(end.getTime() - 7 * DAY);
  const week = await teamActivity(start, end);
  const pipe = await pipelineNow();
  const wonBy = await prismaUnscoped.crmDeal.groupBy({
    by: ['assigneeId'],
    where: { deletedAt: null, stage: { kind: CrmStageKind.WON }, wonAt: { gte: start, lt: end } },
    _sum: { value: true },
    _count: { _all: true },
  });
  const board: CrmEmailItem[] = wonBy
    .sort((a, b) => (b._sum.value ?? 0) - (a._sum.value ?? 0))
    .map((g) => ({ text: members.find((m) => m.id === g.assigneeId)?.name ?? 'Unassigned', aside: `${rupees(g._sum.value ?? 0)} · ${g._count._all} won` }));
  const figures: [string, string][] = [
    ['Won', `${week.won.length} · ${rupees(week.wonValue)}`],
    ['Lost', String(week.lost.length)],
    ['Open pipeline', rupees(pipe.value)],
  ];
  // The funnel by source (L6): where last month's leads are now, and last week's habits.
  const fun = await weeklyFunnelLines(now);
  const sections = (extra: CrmEmailSection[] = []): CrmEmailSection[] => [
    ...extra,
    { heading: 'Funnel by source (leads from the last 30 days)', items: fun.sources, empty: 'No new leads in the last 30 days.' },
    { heading: 'Habits', items: fun.habits },
    { heading: 'Lost reasons last week', items: fun.lost, empty: 'No deals were lost last week.' },
    { heading: 'Won and lost last week', items: week.lines, empty: 'No deals were won or lost last week.' },
    { heading: 'Leaderboard', items: board, empty: 'Nobody won a deal last week.' },
    { heading: 'Activity', items: [{ text: `${week.newContacts} new contacts · ${week.newDeals} new deals · ${week.moves} stage moves · ${week.calls} calls and meetings` }, { text: `Pipeline now: ${pipe.count} open deals, ${rupees(pipe.value)} (weighted ${rupees(pipe.weighted)})` }] },
  ];
  let sent = 0;
  for (const m of members.filter((x) => x.prefs.weekly && inWindow(now, x.prefs.summaryHour))) {
    const open = await prismaUnscoped.crmTask.count({ where: { assigneeId: m.id, done: false, OR: [{ dealId: null }, { deal: { deletedAt: null } }] } });
    const s = await deliver({
      key: `weekly:${m.id}:${date}`,
      kind: 'WEEKLY',
      to: m.email,
      userId: m.id,
      mail: crmEmail({
        title: `CRM week: ${week.won.length} won, ${rupees(week.wonValue)}`,
        intro: `${m.name.split(' ')[0]}, here is how last week went for the team.`,
        badge: 'Weekly summary',
        figures,
        sections: sections([{ heading: 'You', items: [{ text: `${open} open task${open === 1 ? '' : 's'}`, url: crmUrl('home') }] }]),
        cta: { label: 'Open the CRM', url: crmUrl('home') },
        reason: 'Your weekly CRM summary. Turn it off or change its time in your CRM profile.',
      }),
    });
    if (s === 'SENT' || s === 'DRY_RUN') sent++;
  }
  const copy = await superAdminCopyAddress();
  if (copy && inWindow(now, REMIND_HOUR)) {
    const s = await deliver({
      key: `weekly-team:${date}`,
      kind: 'WEEKLY_TEAM',
      to: copy,
      isCopy: true,
      mail: crmEmail({
        title: `CRM team week: ${week.won.length} won, ${rupees(week.wonValue)}`,
        intro: 'Last week for the whole sales team.',
        badge: 'Team summary',
        figures,
        sections: sections(),
        cta: { label: 'Open the CRM', url: crmUrl('home') },
        reason: 'You get this because CRM emails are copied to the super admin. Change it in CRM settings.',
      }),
    });
    if (s === 'SENT' || s === 'DRY_RUN') sent++;
  }
  return sent;
}

// ── The tick ───────────────────────────────────────────────────────────────

/** AI work must never stop the emails: log and carry on. */
async function safely(what: string, f: () => Promise<number>) {
  try {
    return await f();
  } catch (err) {
    // eslint-disable-next-line no-console
    console.error(`[crm] ${what} failed: ${err instanceof Error ? err.message : String(err)}`);
    return 0;
  }
}

export async function tick(now = new Date()) {
  const members = await crmMembersWithPrefs();
  const teamWide = (await getCrmSettings()).teamFollowUps;
  // Gather every follow-up and task reminder due now, then send them together.
  const due = [...(await dueFollowUps(now, members, teamWide)), ...(await dueTasks(now, members))];
  const reminders = await sendReminders(now, due, teamWide);
  // Leads nobody contacted in time (L1): before the alerts flush, after the reminders.
  const lateLeads = await safely('late leads', () => escalateLateLeads(now));
  // Demo reminders (L3): the owner's evening-before and hour-before, the host's 15 minutes.
  const demoReminders = await safely('demo reminders', () => demoRemindersTick(now));
  // Meta leads still waiting for their answers (L4): a token fixed later, Meta briefly down.
  const metaLeads = await safely('meta leads', () => retryMetaLeads(now));
  // Nurture (L6): the month's message in batches, and April's admission-season calls.
  const nurtureSent = await safely('nurture', () => nurtureTick(now));
  const seasonCalls = await safely('season calls', () => seasonCallsTick(now));
  // The trial journey (L5): wins, Trial active, unused trials, nudges, welcome and review.
  let trials = { won: 0, activated: 0, unused: 0, nudges: 0, customer: 0 };
  await safely('trial journey', async () => {
    trials = await trialJourneyTick(now);
    return 0;
  });
  // After the reminders, so this tick's copies can join a batch that is due.
  const alerts = await flushAlerts(now);
  // Scores before the summaries, so the daily focus reads fresh ones.
  const scored = await safely('lead scoring', () => scoreTick(now));
  const daily = await dailies(now, members);
  const weekly = await weeklies(now, members);
  const insights = await safely('monthly insights', () => monthlyInsightsTick(now));
  return { alerts, reminders, lateLeads, demoReminders, metaLeads, trials, nurtureSent, seasonCalls, scored, daily, weekly, insights };
}
