import { CrmActivityType, CrmStageKind } from '@prisma/client';
import { prismaUnscoped } from '../../lib/prisma';
import { isAiConfigured } from '../../lib/openai';
import { BadRequestError, NotFoundError } from '../../lib/errors';
import { getCrmSettings } from './crm-settings.service';
import { istDayStart } from './crm-mail';
import { PROPERTY_TYPE_LABEL, STATUS_LABEL } from './crm-contacts.service';
import { dealRef } from './crm-deals.service';
import { ROLE, aiBlocked, clip, obj, run, str, today, type AiFeature } from './crm-ai.service';
import type { Actor } from './crm-users.service';

/**
 * AI lead scores and the daily focus (C6).
 *
 * Every open deal carries a 0–100 score with a one-line reason. The CRM clock
 * scores deals in batches: any deal never scored, any deal whose stage,
 * value, close date, win chance or contact changed (a "big change"), and
 * every deal once a day after midnight India time. Scores are the one AI
 * output saved without a person confirming it; they never touch the deal's
 * updatedAt or its timeline, so sorting by "recently updated" and the stale
 * deals list still mean what people did.
 */

const HOUR = 3_600_000;
const DAY = 86_400_000;
const BATCH = 20;
const MAX_BATCHES_PER_TICK = 3;

/** True when a feature is switched on and the server has a key (budget aside). */
export async function aiFeatureOn(feature: AiFeature) {
  if (!isAiConfigured()) return false;
  const s = await getCrmSettings();
  return s.aiEnabled && s.aiFeatures.includes(feature);
}

/** What a score is based on; when it changes, the deal is scored again. */
export function scoreKeyOf(d: { stageId: string; value: number; expectedCloseDate: Date | null; probability: number | null; contactId: string | null }) {
  return [d.stageId, d.value, d.expectedCloseDate?.toISOString() ?? '', d.probability ?? '', d.contactId ?? ''].join('|');
}

const days = (from: Date, to: Date) => Math.floor((to.getTime() - from.getTime()) / DAY);

/** "in 3 days", "today", "2 days ago". */
function relative(at: Date | null, now: Date) {
  if (!at) return 'not set';
  const d = Math.round((istDayStart(at).getTime() - istDayStart(now).getTime()) / DAY);
  return d === 0 ? 'today' : d > 0 ? `in ${d} day${d === 1 ? '' : 's'}` : `${-d} day${d === -1 ? '' : 's'} ago`;
}

/** Win rates over the last year, overall and by source and property type. */
async function baselines(now: Date) {
  const closed = await prismaUnscoped.crmDeal.findMany({
    where: { deletedAt: null, stage: { kind: { in: [CrmStageKind.WON, CrmStageKind.LOST] } }, OR: [{ wonAt: { gte: new Date(now.getTime() - 365 * DAY) } }, { lostAt: { gte: new Date(now.getTime() - 365 * DAY) } }] },
    select: { source: true, stage: { select: { kind: true } }, contact: { select: { propertyType: true, source: true } } },
  });
  const rate = (rows: typeof closed) => (rows.length ? `${Math.round((rows.filter((r) => r.stage.kind === CrmStageKind.WON).length / rows.length) * 100)}% of ${rows.length}` : 'no history');
  const by = (key: (r: (typeof closed)[number]) => string | null | undefined) => {
    const groups = new Map<string, typeof closed>();
    for (const r of closed) {
      const k = key(r);
      if (!k) continue;
      groups.set(k, [...(groups.get(k) ?? []), r]);
    }
    return [...groups.entries()].filter(([, v]) => v.length >= 2).map(([k, v]) => `${k}: ${rate(v)}`).join('; ') || 'too few closed deals';
  };
  return `Closed deals in the last year — won ${rate(closed)}. By source: ${by((r) => r.source ?? r.contact?.source)}. By property type: ${by((r) => (r.contact?.propertyType ? PROPERTY_TYPE_LABEL[r.contact.propertyType] : null))}.`;
}

/** One compact line per deal, keyed by its DEAL-0001 reference. */
async function scoringLines(ids: string[], now: Date) {
  const [deals, stages, recent, last] = await Promise.all([
    prismaUnscoped.crmDeal.findMany({
      where: { id: { in: ids }, deletedAt: null, stage: { kind: CrmStageKind.OPEN } },
      include: {
        stage: { select: { name: true, position: true, probability: true } },
        contact: { select: { propertyType: true, approxBeds: true, city: true, status: true, source: true, designation: true } },
        tasks: { where: { done: false }, select: { dueAt: true } },
      },
    }),
    prismaUnscoped.crmStage.findMany({ where: { kind: CrmStageKind.OPEN }, orderBy: { position: 'asc' }, select: { id: true } }),
    prismaUnscoped.crmActivity.groupBy({ by: ['dealId', 'type'], where: { dealId: { in: ids }, createdAt: { gte: new Date(now.getTime() - 30 * DAY), lte: now } }, _count: { _all: true } }),
    prismaUnscoped.crmActivity.groupBy({ by: ['dealId'], where: { dealId: { in: ids }, createdAt: { lte: now } }, _max: { createdAt: true } }),
  ]);
  const count = (dealId: string, type: CrmActivityType) => recent.find((r) => r.dealId === dealId && r.type === type)?._count._all ?? 0;
  return deals.map((d) => {
    const lastAt = last.find((l) => l.dealId === d.id)?._max.createdAt ?? d.createdAt;
    const c = d.contact;
    return {
      deal: d,
      line: {
        ref: dealRef(d.number),
        title: clip(d.title, 80),
        valueInr: d.value,
        stage: `${d.stage.name} (step ${stages.findIndex((s) => s.id === d.stageId) + 1} of ${stages.length})`,
        winChance: d.probability ?? d.stage.probability,
        daysOpen: days(d.createdAt, now),
        daysInStage: days(d.stageChangedAt, now),
        daysSinceLastActivity: days(lastAt, now),
        last30Days: { calls: count(d.id, CrmActivityType.CALL), meetings: count(d.id, CrmActivityType.MEETING), emails: count(d.id, CrmActivityType.EMAIL), notes: count(d.id, CrmActivityType.NOTE), stageMoves: count(d.id, CrmActivityType.STAGE_CHANGED) },
        openTasks: d.tasks.length,
        overdueTasks: d.tasks.filter((t) => t.dueAt && t.dueAt < now).length,
        nextAction: d.nextActionAt ? `${clip(d.nextStep, 80) || 'something'} ${relative(d.nextActionAt, now)}` : 'none planned',
        expectedClose: relative(d.expectedCloseDate, now),
        source: d.source ?? c?.source ?? null,
        planInterest: d.planInterest,
        beds: d.beds ?? c?.approxBeds ?? null,
        contact: c ? { runs: c.propertyType ? PROPERTY_TYPE_LABEL[c.propertyType] : null, city: c.city, status: STATUS_LABEL[c.status], role: c.designation } : null,
      },
    };
  });
}

const SCORING = `Score each open deal from 0 to 100: how likely it is to be won in the next 90 days.
Weigh: the stage and its win chance; momentum (recent calls, meetings and stage moves, days since the last activity, days stuck in this stage); overdue tasks or next actions; an expected close date already passed; fit (a hostel, PG, dormitory or university with more beds is a bigger, better fit); and the win rates below for its source and property type.
Calibrate: an untouched new lead is 10–30; a deal far along with recent activity is 60–90; a deal quiet for weeks or past its close date rarely scores above 40.
"reason" is one line under 110 characters naming the main driver, specific to the deal (e.g. "Demo done, two calls this week, 300-bed university — strong fit"). Score every deal given, using its ref.`;

/** Score up to BATCH open deals with one call, and save the results. */
export async function scoreDeals(ids: string[], actor: Actor | null, now = new Date()) {
  const rows = await scoringLines(ids.slice(0, BATCH), now);
  if (!rows.length) return [];
  const r = await run<{ scores: { ref: string; score: number; reason: string }[] }>('score', actor, {
    name: 'crm_lead_scores',
    system: `${ROLE}\n${today()}\n${SCORING}\n${await baselines(now)}`,
    user: `<data>${JSON.stringify(rows.map((x) => x.line))}</data>`,
    maxTokens: 400 + rows.length * 120,
    schema: obj({ scores: { type: 'array', items: obj({ ref: str, score: { type: 'integer' }, reason: str }) } }),
  });
  const saved: { id: string; score: number; reason: string }[] = [];
  for (const row of rows) {
    const s = r.scores.find((x) => x.ref.trim().toUpperCase() === row.line.ref);
    if (!s || !Number.isFinite(s.score)) continue;
    const score = Math.max(0, Math.min(100, Math.round(s.score)));
    const reason = clip(s.reason, 160) || 'No reason given';
    // Raw SQL so the deal's updatedAt stays what people did. The session may
    // not be in UTC, so the instant is written as UTC explicitly.
    await prismaUnscoped.$executeRaw`UPDATE "CrmDeal" SET "aiScore" = ${score}, "aiScoreReason" = ${reason}, "aiScoredAt" = (${now.toISOString()}::timestamptz AT TIME ZONE 'UTC'), "aiScoreKey" = ${scoreKeyOf(row.deal)} WHERE "id" = ${row.deal.id}`;
    saved.push({ id: row.deal.id, score, reason });
  }
  // The call list sorts contacts by their best open deal's score (L6).
  const contactIds = [...new Set(rows.map((r) => r.deal.contactId).filter((x): x is string => !!x))];
  if (contactIds.length) {
    await prismaUnscoped.$executeRaw`UPDATE "CrmContact" c SET "leadScore" = s.score FROM (SELECT d."contactId", MAX(d."aiScore") AS score FROM "CrmDeal" d JOIN "CrmStage" st ON st."id" = d."stageId" WHERE d."deletedAt" IS NULL AND st."kind" = 'OPEN' AND d."contactId" = ANY(${contactIds}::text[]) GROUP BY d."contactId") s WHERE c."id" = s."contactId"`;
  }
  return saved;
}

/** Score one deal now, from its panel. */
export async function rescoreDeal(id: string, actor: Actor) {
  const d = await prismaUnscoped.crmDeal.findFirst({ where: { id, deletedAt: null }, select: { stage: { select: { kind: true } } } });
  if (!d) throw new NotFoundError('Deal not found');
  if (d.stage.kind !== CrmStageKind.OPEN) throw new BadRequestError('Only open deals are scored.', 'DEAL_CLOSED');
  const now = new Date();
  const [s] = await scoreDeals([id], actor, now);
  if (!s) throw new BadRequestError('The AI did not score this deal. Try again.', 'AI_NO_SCORE');
  return { aiScore: s.score, aiScoreReason: s.reason, aiScoredAt: now };
}

// Background state: a deal the AI skipped is not asked about again for an
// hour, and a failing provider pauses scoring for half an hour.
const skipped = new Map<string, number>();
let pausedUntil = 0;

/** The clock's part: score what is due, a few batches per tick. */
export async function scoreTick(now = new Date()) {
  // A won or lost deal drops its score, so sorting by score ranks open deals
  // only; reopening it is a big change and it is scored afresh.
  await prismaUnscoped.$executeRaw`UPDATE "CrmDeal" d SET "aiScore" = NULL, "aiScoreReason" = NULL, "aiScoredAt" = NULL, "aiScoreKey" = NULL FROM "CrmStage" s WHERE d."stageId" = s."id" AND s."kind" <> 'OPEN' AND d."aiScore" IS NOT NULL`;
  if (Date.now() < pausedUntil || (await aiBlocked('score'))) return 0;
  const open = await prismaUnscoped.crmDeal.findMany({
    where: { deletedAt: null, stage: { kind: CrmStageKind.OPEN } },
    select: { id: true, stageId: true, value: true, expectedCloseDate: true, probability: true, contactId: true, aiScoreKey: true, aiScoredAt: true },
  });
  const dayStart = istDayStart(now);
  const urgent = (d: (typeof open)[number]) => !d.aiScoredAt || scoreKeyOf(d) !== d.aiScoreKey;
  const due = open
    .filter((d) => urgent(d) || d.aiScoredAt! < dayStart)
    .filter((d) => (skipped.get(d.id) ?? 0) < Date.now() - HOUR)
    .sort((a, b) => Number(urgent(b)) - Number(urgent(a)))
    .slice(0, BATCH * MAX_BATCHES_PER_TICK);
  let scored = 0;
  for (let i = 0; i < due.length; i += BATCH) {
    const chunk = due.slice(i, i + BATCH).map((d) => d.id);
    try {
      const saved = await scoreDeals(chunk, null, now);
      scored += saved.length;
      for (const id of chunk) if (!saved.some((s) => s.id === id)) skipped.set(id, Date.now());
    } catch (err) {
      pausedUntil = Date.now() + 30 * 60_000;
      // eslint-disable-next-line no-console
      console.error(`[crm] lead scoring paused: ${err instanceof Error ? err.message : String(err)}`);
      break;
    }
  }
  return scored;
}

// ── The daily focus ────────────────────────────────────────────────────────

export interface DailyFocus {
  items: { dealId: string; ref: string; title: string; why: string; score: number | null }[];
  risks: string[];
}

/**
 * "Focus on these 3 deals today", and the risks the AI sees, for the top of
 * one person's daily summary. Null when AI is off, there is nothing to focus
 * on, or the call fails — the summary goes out without it.
 */
export async function dailyFocus(member: { id: string; name: string }, now = new Date()): Promise<DailyFocus | null> {
  if (await aiBlocked('focus')) return null;
  const deals = await prismaUnscoped.crmDeal.findMany({
    where: { assigneeId: member.id, deletedAt: null, stage: { kind: CrmStageKind.OPEN } },
    orderBy: [{ aiScore: { sort: 'desc', nulls: 'last' } }, { nextActionAt: { sort: 'asc', nulls: 'last' } }],
    take: 30,
    include: { stage: { select: { name: true } }, tasks: { where: { done: false }, select: { dueAt: true } } },
  });
  if (!deals.length) return null;
  const last = await prismaUnscoped.crmActivity.groupBy({ by: ['dealId'], where: { dealId: { in: deals.map((d) => d.id) }, createdAt: { lte: now } }, _max: { createdAt: true } });
  const lines = deals.map((d) => ({
    ref: dealRef(d.number),
    title: clip(d.title, 80),
    valueInr: d.value,
    stage: d.stage.name,
    score: d.aiScore,
    scoreReason: d.aiScoreReason,
    nextAction: d.nextActionAt ? `${clip(d.nextStep, 80) || 'something'} ${relative(d.nextActionAt, now)}` : 'none planned',
    expectedClose: relative(d.expectedCloseDate, now),
    daysSinceLastActivity: days(last.find((l) => l.dealId === d.id)?._max.createdAt ?? d.createdAt, now),
    overdueTasks: d.tasks.filter((t) => t.dueAt && t.dueAt < now).length,
  }));
  try {
    const r = await run<{ focus: { ref: string; why: string }[]; risks: string[] }>('focus', null, {
      name: 'crm_daily_focus',
      system: `${ROLE}\n${today()}\nThese are ${member.name}'s open deals. Pick the (up to) 3 deals they should focus on today and, for each, say what to do and why in under 20 words. Prefer deals with a high score and something due, a close date slipping, or a good deal going quiet. Then name up to 2 risks across their pipeline, each under 25 words. Use only the facts given.`,
      user: `<data>${JSON.stringify(lines)}</data>`,
      maxTokens: 900,
      schema: obj({ focus: { type: 'array', items: obj({ ref: str, why: str }) }, risks: { type: 'array', items: str } }),
    });
    const items = r.focus
      .map((f) => ({ f, d: deals.find((d) => dealRef(d.number) === f.ref.trim().toUpperCase()) }))
      .filter((x): x is { f: { ref: string; why: string }; d: (typeof deals)[number] } => !!x.d)
      .filter((x, i, all) => all.findIndex((y) => y.d.id === x.d.id) === i)
      .slice(0, 3)
      .map(({ f, d }) => ({ dealId: d.id, ref: dealRef(d.number), title: d.title, why: clip(f.why, 160), score: d.aiScore }));
    return items.length ? { items, risks: r.risks.slice(0, 2).map((x) => clip(x, 200)).filter(Boolean) } : null;
  } catch {
    return null;
  }
}

/** The best-scored open deals across the team, for the super admin's summary. */
export async function topScored(limit = 5) {
  if (!(await aiFeatureOn('score'))) return [];
  return prismaUnscoped.crmDeal.findMany({
    where: { deletedAt: null, stage: { kind: CrmStageKind.OPEN }, aiScore: { not: null } },
    orderBy: [{ aiScore: 'desc' }, { value: 'desc' }],
    take: limit,
    select: { id: true, number: true, title: true, value: true, aiScore: true, aiScoreReason: true, assignee: { select: { name: true } } },
  });
}
