import type { Prisma } from "@prisma/client";
import { prisma } from "../prisma.js";
import { computeDropoutProjections } from "./dropoutProtocol.js";
import { computeAttendanceCoverageForTrainingScope } from "./attendanceCoverageSlots.js";
import { ALERT_RULE_DEFAULTS, ALERT_TYPES, type AlertSeverity, type AlertType } from "./alertTypes.js";

type Candidate = {
  type: AlertType;
  severity: AlertSeverity;
  title: string;
  message: string;
  scopeKey: string;
  dedupeKey: string;
  smtpEnabled: boolean;
  cooldownMinutes: number;
  trainingProviderId?: bigint | null;
  trainingId?: bigint | null;
  cohortId?: bigint | null;
  batchId?: bigint | null;
  recipientUserIds: bigint[];
  meta?: Prisma.InputJsonValue;
};

function toMetaRecord(meta: unknown): Record<string, unknown> {
  if (!meta || typeof meta !== "object" || Array.isArray(meta)) return {};
  return meta as Record<string, unknown>;
}

function dropoutMeaningfulFingerprint(meta: unknown) {
  const m = toMetaRecord(meta);
  const sharePct = Number(m.sharePct ?? 0);
  return JSON.stringify({
    atRisk: Number(m.atRisk ?? 0),
    finalDropout: Number(m.finalDropout ?? 0),
    tpReportedDropout: Number(m.tpReportedDropout ?? 0),
    total: Number(m.total ?? 0),
    shareBucket: Math.floor(sharePct / 5), // 5% bands to avoid noisy re-notifications.
  });
}

function dayKey(value: Date) {
  return value.toISOString().slice(0, 10);
}

function dateOnlyUtc(value: Date) {
  return new Date(`${value.toISOString().slice(0, 10)}T00:00:00.000Z`);
}

function plusDays(value: Date, days: number) {
  const out = dateOnlyUtc(value);
  out.setUTCDate(out.getUTCDate() + days);
  return out;
}

function toPct(numerator: number, denominator: number) {
  if (!denominator) return 0;
  return Math.round((numerator / denominator) * 1000) / 10;
}

function uniqueIds(values: bigint[]) {
  return [...new Set(values.map((x) => x.toString()))].map((x) => BigInt(x));
}
function uniqueStrings(values: string[]) {
  return [...new Set(values)];
}

function daysUntil(from: Date, to: Date) {
  return Math.floor((dateOnlyUtc(to).getTime() - dateOnlyUtc(from).getTime()) / (24 * 60 * 60 * 1000));
}

async function attendanceCoverage(projectId: bigint, trainingProviderId: bigint, trainingId: bigint, cohortId: bigint | null) {
  const { expectedSlots, submittedRows } = await computeAttendanceCoverageForTrainingScope({
    projectId,
    trainingProviderId,
    trainingId,
    cohortId,
    batchId: null,
  });
  return { expectedSlots, submittedRows };
}

function resolveRule(
  rulesByType: Map<string, { isEnabled: boolean; inAppEnabled: boolean; smtpEnabled: boolean; severity: string; cooldownMinutes: number }>,
  type: AlertType,
) {
  const stored = rulesByType.get(type);
  const defaults = ALERT_RULE_DEFAULTS[type];
  return {
    isEnabled: stored?.isEnabled ?? true,
    inAppEnabled: stored?.inAppEnabled ?? true,
    smtpEnabled: stored?.smtpEnabled ?? defaults.smtpEnabled,
    severity: (stored?.severity as AlertSeverity | undefined) ?? defaults.severity,
    cooldownMinutes: Math.max(1, stored?.cooldownMinutes ?? defaults.cooldownMinutes),
  };
}

export async function evaluateProjectAlerts(projectId: bigint, now = new Date()) {
  const db = prisma as any;
  const today = dateOnlyUtc(now);
  const [projectUsers, providers, rules] = await Promise.all([
    prisma.projectUser.findMany({
      where: { projectId },
      select: { userId: true, projectRole: true },
    }),
    prisma.trainingProvider.findMany({
      where: { projectId },
      select: { id: true, userId: true, tpCode: true, name: true },
    }),
    db.alertRule.findMany({
      where: { projectId },
      select: { alertType: true, isEnabled: true, inAppEnabled: true, smtpEnabled: true, severity: true, cooldownMinutes: true },
    }),
  ]);
  const adminUserIds = uniqueIds(projectUsers.filter((x) => x.projectRole !== "tp").map((x) => x.userId));
  const providerUserIdByProvider = new Map<string, bigint>();
  const providerById = new Map<string, { name: string; tpCode: string }>();
  for (const p of providers) {
    if (p.userId) providerUserIdByProvider.set(p.id.toString(), p.userId);
    providerById.set(p.id.toString(), { name: p.name, tpCode: p.tpCode });
  }
  const rulesByType = new Map<string, { isEnabled: boolean; inAppEnabled: boolean; smtpEnabled: boolean; severity: string; cooldownMinutes: number }>(
    rules.map((r: { alertType: string; isEnabled: boolean; inAppEnabled: boolean; smtpEnabled: boolean; severity: string; cooldownMinutes: number }) => [r.alertType, r]),
  );

  const candidates: Candidate[] = [];

  const activities = await prisma.projectActivity.findMany({
    where: { projectId, isActive: true, submissionScope: "delivery" },
    include: {
      rules: { where: { isActive: true } },
      assignments: { select: { trainingProviderId: true } },
    },
  });
  const trainings = await prisma.training.findMany({
    where: { projectId },
    select: {
      id: true,
      title: true,
      trainingProviderId: true,
      trainingDurationId: true,
      startDate: true,
      timelineAnchorDate: true,
      cohorts: { select: { id: true, code: true, startDate: true, timelineAnchorDate: true } },
    },
  });
  const trainingIdsForAlerts = trainings.map((t) => t.id);
  const deliveryBatchesForAlerts =
    trainingIdsForAlerts.length > 0
      ? await prisma.trainingBatch.findMany({
          where: { projectId, trainingId: { in: trainingIdsForAlerts } },
          select: {
            id: true,
            trainingId: true,
            cohortId: true,
            code: true,
            startDate: true,
            timelineAnchorDate: true,
          },
        })
      : [];
  const batchesByTrainingId = new Map<string, typeof deliveryBatchesForAlerts>();
  for (const b of deliveryBatchesForAlerts) {
    const k = b.trainingId.toString();
    const cur = batchesByTrainingId.get(k) ?? [];
    cur.push(b);
    batchesByTrainingId.set(k, cur);
  }
  const submissions = await prisma.tpActivitySubmission.findMany({
    where: { projectId },
    select: {
      projectActivityId: true,
      trainingProviderId: true,
      trainingId: true,
      cohortId: true,
      batchId: true,
      submittedAt: true,
      status: true,
      meta: true,
    },
  });
  const submittedByWindow = new Set<string>();
  for (const s of submissions) {
    const meta = (s.meta ?? {}) as Record<string, unknown>;
    const dueDate = typeof meta.windowEndDateEffective === "string" ? meta.windowEndDateEffective : null;
    if (!dueDate) continue;
    const key = `${s.projectActivityId.toString()}:${s.trainingProviderId.toString()}:${s.trainingId?.toString() ?? "0"}:${s.cohortId?.toString() ?? "0"}:${s.batchId?.toString() ?? "0"}:${dueDate}`;
    submittedByWindow.add(key);
  }

  for (const activity of activities) {
    const assignedSet = new Set(activity.assignments.map((a) => a.trainingProviderId.toString()));
    const activityTrainings = trainings.filter((t) => {
      if (!assignedSet.size) return true;
      return assignedSet.has(t.trainingProviderId.toString());
    });
    for (const training of activityTrainings) {
      const rule = activity.rules.find((r) => r.trainingDurationId === training.trainingDurationId);
      if (!rule || rule.endOffsetDays == null) continue;
      const alertDueSoon = resolveRule(rulesByType, ALERT_TYPES.ACTIVITY_DUE_SOON);
      const alertOverdue = resolveRule(rulesByType, ALERT_TYPES.ACTIVITY_OVERDUE);
      if (!alertDueSoon.isEnabled && !alertOverdue.isEnabled) continue;
      type ActivityScope = {
        cohortId: bigint | null;
        batchId: bigint | null;
        cohortLabel: string | null;
        anchorDate: Date | null | undefined;
      };

      let scopes: ActivityScope[];
      const anchor = rule.anchorType;
      if (anchor === "batch_start" || anchor === "batch_anchor") {
        const bList = batchesByTrainingId.get(training.id.toString()) ?? [];
        scopes = bList.map((b) => ({
          cohortId: b.cohortId,
          batchId: b.id,
          cohortLabel: b.code,
          anchorDate:
            anchor === "batch_anchor"
              ? b.timelineAnchorDate ?? b.startDate
              : b.startDate ?? b.timelineAnchorDate,
        }));
      } else if (training.cohorts.length) {
        scopes = training.cohorts.map((c) => ({
          cohortId: c.id,
          batchId: null,
          cohortLabel: c.code,
          anchorDate:
            anchor === "cohort_anchor"
              ? c.timelineAnchorDate ?? c.startDate
              : c.startDate ?? c.timelineAnchorDate,
        }));
      } else {
        scopes = [
          {
            cohortId: null,
            batchId: null,
            cohortLabel: null,
            anchorDate:
              anchor === "training_anchor"
                ? training.timelineAnchorDate ?? training.startDate
                : training.startDate ?? training.timelineAnchorDate,
          },
        ];
      }

      for (const scope of scopes) {
        if (!scope.anchorDate) continue;
        const endDate = plusDays(scope.anchorDate, rule.endOffsetDays ?? 0);
        const dueDate = plusDays(endDate, Math.max(0, rule.graceDaysAfterEnd ?? 0));
        const dKey = dayKey(dueDate);
        const submissionKey = `${activity.id.toString()}:${training.trainingProviderId.toString()}:${training.id.toString()}:${scope.cohortId?.toString() ?? "0"}:${scope.batchId?.toString() ?? "0"}:${dKey}`;
        if (submittedByWindow.has(submissionKey)) continue;
        const delta = daysUntil(today, dueDate);
        const providerUser = providerUserIdByProvider.get(training.trainingProviderId.toString());
        const recipients = uniqueIds([...(providerUser ? [providerUser] : []), ...adminUserIds]);
        if (!recipients.length) continue;

        const scopeHint = scope.batchId
          ? ` (delivery batch ${scope.cohortLabel ?? scope.batchId.toString()})`
          : scope.cohortLabel
            ? ` (cohort ${scope.cohortLabel})`
            : "";
        const scopeSeg = `${scope.cohortId?.toString() ?? "0"}:${scope.batchId?.toString() ?? "0"}`;

        if (alertDueSoon.isEnabled && (delta === 7 || delta === 2)) {
          candidates.push({
            type: ALERT_TYPES.ACTIVITY_DUE_SOON,
            severity: alertDueSoon.severity,
            title: `Activity due in ${delta} days: ${activity.name}`,
            message: `${activity.code} for training "${training.title}" is due on ${dKey}${scopeHint}.`,
            scopeKey: `${activity.id.toString()}:${training.id.toString()}:${scopeSeg}:${dKey}`,
            dedupeKey: `${ALERT_TYPES.ACTIVITY_DUE_SOON}:${activity.id.toString()}:${training.id.toString()}:${scopeSeg}:${dKey}:${delta}`,
            smtpEnabled: alertDueSoon.smtpEnabled,
            cooldownMinutes: alertDueSoon.cooldownMinutes,
            trainingProviderId: training.trainingProviderId,
            trainingId: training.id,
            cohortId: scope.cohortId,
            batchId: scope.batchId,
            recipientUserIds: recipients,
            meta: { dueDate: dKey, daysRemaining: delta, activityCode: activity.code, trainingTitle: training.title },
          });
        }
        if (alertOverdue.isEnabled && delta < 0 && Math.abs(delta) % 3 === 0) {
          candidates.push({
            type: ALERT_TYPES.ACTIVITY_OVERDUE,
            severity: alertOverdue.severity,
            title: `Activity overdue: ${activity.name}`,
            message: `${activity.code} for training "${training.title}" is overdue by ${Math.abs(delta)} day(s). Due date was ${dKey}${scopeHint}.`,
            scopeKey: `${activity.id.toString()}:${training.id.toString()}:${scopeSeg}:${dKey}`,
            dedupeKey: `${ALERT_TYPES.ACTIVITY_OVERDUE}:${activity.id.toString()}:${training.id.toString()}:${scopeSeg}:${dKey}`,
            smtpEnabled: alertOverdue.smtpEnabled,
            cooldownMinutes: alertOverdue.cooldownMinutes,
            trainingProviderId: training.trainingProviderId,
            trainingId: training.id,
            cohortId: scope.cohortId,
            batchId: scope.batchId,
            recipientUserIds: recipients,
            meta: { dueDate: dKey, overdueDays: Math.abs(delta), activityCode: activity.code, trainingTitle: training.title },
          });
        }
      }
    }
  }

  const attendanceRule = resolveRule(rulesByType, ALERT_TYPES.ATTENDANCE_COVERAGE_LOW);
  if (attendanceRule.isEnabled) {
    for (const training of trainings) {
      const scopes = training.cohorts.length ? training.cohorts.map((c) => c.id) : [null];
      for (const cohortId of scopes) {
        const coverage = await attendanceCoverage(projectId, training.trainingProviderId, training.id, cohortId);
        if (coverage.expectedSlots < 20) continue;
        const pct = toPct(coverage.submittedRows, coverage.expectedSlots);
        if (pct >= 85) continue;
        const providerUser = providerUserIdByProvider.get(training.trainingProviderId.toString());
        const recipients = uniqueIds([...(providerUser ? [providerUser] : []), ...adminUserIds]);
        if (!recipients.length) continue;
        candidates.push({
          type: ALERT_TYPES.ATTENDANCE_COVERAGE_LOW,
          severity: attendanceRule.severity,
          title: `Attendance coverage below threshold`,
          message: `Coverage is ${pct}% (${coverage.submittedRows}/${coverage.expectedSlots}) for training "${training.title}"${cohortId ? " cohort scope" : ""}.`,
          scopeKey: `${training.id.toString()}:${cohortId?.toString() ?? "0"}`,
          dedupeKey: `${ALERT_TYPES.ATTENDANCE_COVERAGE_LOW}:${training.id.toString()}:${cohortId?.toString() ?? "0"}`,
          smtpEnabled: attendanceRule.smtpEnabled,
          cooldownMinutes: attendanceRule.cooldownMinutes,
          trainingProviderId: training.trainingProviderId,
          trainingId: training.id,
          cohortId,
          recipientUserIds: recipients,
          meta: { coveragePct: pct, submittedRows: coverage.submittedRows, expectedSlots: coverage.expectedSlots },
        });
      }
    }
  }

  const dropoutRule = resolveRule(rulesByType, ALERT_TYPES.DROPOUT_RISK_SUMMARY);
  if (dropoutRule.isEnabled) {
    const projections = await computeDropoutProjections({ projectId, now: today });
    const byProvider = new Map<
      string,
      {
        atRisk: number;
        finalDropout: number;
        tpReported: number;
        total: number;
        flaggedRows: Array<{
          traineeId: string;
          traineeUniqueId: string;
          traineeName: string;
          trainingId: string;
          cohortId: string | null;
          attendancePctToDate: number;
          maxRecoverablePct: number;
          reason: "final_dropout" | "high_risk";
        }>;
      }
    >();
    for (const row of projections) {
      const key = row.trainingProviderId.toString();
      const cur = byProvider.get(key) ?? { atRisk: 0, finalDropout: 0, tpReported: 0, total: 0, flaggedRows: [] };
      cur.total += 1;
      if (row.tpReportedDropout) cur.tpReported += 1;
      // Risk should be based on end-of-training recoverability, not short early-session attendance snapshots.
      const highRisk = !row.systemDropoutFinal && row.possibleToDate >= 10 && row.maxRecoverablePct < 80;
      if (row.systemDropoutFinal || highRisk) {
        cur.atRisk += 1;
        if (row.systemDropoutFinal) cur.finalDropout += 1;
        cur.flaggedRows.push({
          traineeId: row.traineeId.toString(),
          traineeUniqueId: row.traineeUniqueId,
          traineeName: row.traineeName,
          trainingId: row.trainingId.toString(),
          cohortId: row.cohortId ? row.cohortId.toString() : null,
          attendancePctToDate: row.attendancePctToDate,
          maxRecoverablePct: row.maxRecoverablePct,
          reason: row.systemDropoutFinal ? "final_dropout" : "high_risk",
        });
      }
      byProvider.set(key, cur);
    }
    const trainingIds = uniqueStrings(
      [...byProvider.values()].flatMap((stat) => stat.flaggedRows.map((r) => r.trainingId)),
    ).map((x) => BigInt(x));
    const cohortIds = uniqueStrings(
      [...byProvider.values()].flatMap((stat) => stat.flaggedRows.map((r) => r.cohortId).filter((x): x is string => Boolean(x))),
    ).map((x) => BigInt(x));
    const [trainingRows, cohortRows] = await Promise.all([
      trainingIds.length
        ? prisma.training.findMany({ where: { id: { in: trainingIds } }, select: { id: true, title: true } })
        : Promise.resolve([]),
      cohortIds.length
        ? prisma.trainingCohort.findMany({ where: { id: { in: cohortIds } }, select: { id: true, code: true } })
        : Promise.resolve([]),
    ]);
    const trainingTitleById = new Map(trainingRows.map((x) => [x.id.toString(), x.title]));
    const cohortCodeById = new Map(cohortRows.map((x) => [x.id.toString(), x.code]));
    for (const [providerId, stat] of byProvider.entries()) {
      const share = stat.total > 0 ? stat.atRisk / stat.total : 0;
      if (stat.atRisk < 3 && share < 0.1) continue;
      const providerUser = providerUserIdByProvider.get(providerId);
      const recipients = uniqueIds([...(providerUser ? [providerUser] : []), ...adminUserIds]);
      if (!recipients.length) continue;
      const providerMeta = providerById.get(providerId);
      const groupMap = new Map<string, { trainingId: string; cohortId: string | null; count: number }>();
      for (const row of stat.flaggedRows) {
        const key = `${row.trainingId}:${row.cohortId ?? "none"}`;
        const current = groupMap.get(key) ?? { trainingId: row.trainingId, cohortId: row.cohortId, count: 0 };
        current.count += 1;
        groupMap.set(key, current);
      }
      const groups = [...groupMap.values()]
        .sort((a, b) => b.count - a.count)
        .slice(0, 6)
        .map((g) => ({
          trainingId: g.trainingId,
          trainingTitle: trainingTitleById.get(g.trainingId) ?? `Training ${g.trainingId}`,
          cohortId: g.cohortId,
          cohortCode: g.cohortId ? (cohortCodeById.get(g.cohortId) ?? g.cohortId) : null,
          atRiskCount: g.count,
        }));
      const sampleTrainees = stat.flaggedRows
        .sort((a, b) => {
          if (a.reason !== b.reason) return a.reason === "final_dropout" ? -1 : 1;
          return a.maxRecoverablePct - b.maxRecoverablePct;
        })
        .slice(0, 12)
        .map((r) => ({
          traineeId: r.traineeId,
          traineeUniqueId: r.traineeUniqueId,
          traineeName: r.traineeName,
          trainingId: r.trainingId,
          trainingTitle: trainingTitleById.get(r.trainingId) ?? `Training ${r.trainingId}`,
          cohortId: r.cohortId,
          cohortCode: r.cohortId ? (cohortCodeById.get(r.cohortId) ?? r.cohortId) : null,
          attendancePctToDate: r.attendancePctToDate,
          maxRecoverablePct: r.maxRecoverablePct,
          reason: r.reason,
        }));
      candidates.push({
        type: ALERT_TYPES.DROPOUT_RISK_SUMMARY,
        severity: dropoutRule.severity,
        title: `Dropout risk signal detected`,
        message: `${providerMeta?.tpCode ?? providerId} - ${providerMeta?.name ?? "Training Provider"}: ${stat.atRisk} of ${stat.total} trainees flagged (${Math.round(share * 1000) / 10}%).`,
        scopeKey: providerId,
        dedupeKey: `${ALERT_TYPES.DROPOUT_RISK_SUMMARY}:${providerId}`,
        smtpEnabled: dropoutRule.smtpEnabled,
        cooldownMinutes: dropoutRule.cooldownMinutes,
        trainingProviderId: BigInt(providerId),
        recipientUserIds: recipients,
        meta: {
          providerId,
          providerCode: providerMeta?.tpCode ?? null,
          providerName: providerMeta?.name ?? null,
          atRisk: stat.atRisk,
          finalDropout: stat.finalDropout,
          tpReportedDropout: stat.tpReported,
          total: stat.total,
          sharePct: Math.round(share * 1000) / 10,
          groups,
          sampleTrainees,
        },
      });
    }
  }

  const nowDate = new Date();
  const written: Array<{ event: any; recipientUserIds: bigint[]; smtpEnabled: boolean; cooldownMinutes: number }> = [];
  for (const c of candidates) {
    const existing = await db.alertEvent.findUnique({
      where: { projectId_dedupeKey: { projectId, dedupeKey: c.dedupeKey } },
      select: { id: true, lastNotifiedAt: true, notifyAfter: true, status: true, title: true, message: true, meta: true },
    });
    const nextMetaText =
      c.type === ALERT_TYPES.DROPOUT_RISK_SUMMARY
        ? dropoutMeaningfulFingerprint(c.meta)
        : JSON.stringify(c.meta ?? null);
    const existingMetaText = existing
      ? c.type === ALERT_TYPES.DROPOUT_RISK_SUMMARY
        ? dropoutMeaningfulFingerprint(existing.meta)
        : JSON.stringify(existing.meta ?? null)
      : null;
    const hasMeaningfulChange = Boolean(
      existing &&
      (existing.status !== "open" || existing.title !== c.title || existing.message !== c.message || existingMetaText !== nextMetaText),
    );
    const event = existing
      ? hasMeaningfulChange
        ? await db.alertEvent.update({
            where: { id: existing.id },
            data: {
              alertType: c.type,
              severity: c.severity,
              title: c.title,
              message: c.message,
              scopeKey: c.scopeKey,
              batchId: c.batchId ?? null,
              status: "open",
              lastSeenAt: nowDate,
              resolvedAt: null,
              notifyAfter: existing.notifyAfter ?? nowDate,
              meta: c.meta,
            },
          })
        : existing
      : await db.alertEvent.create({
          data: {
            projectId,
            trainingProviderId: c.trainingProviderId ?? null,
            trainingId: c.trainingId ?? null,
            cohortId: c.cohortId ?? null,
            batchId: c.batchId ?? null,
            alertType: c.type,
            severity: c.severity,
            title: c.title,
            message: c.message,
            scopeKey: c.scopeKey,
            dedupeKey: c.dedupeKey,
            status: "open",
            firstSeenAt: nowDate,
            lastSeenAt: nowDate,
            notifyAfter:
              c.type === ALERT_TYPES.ATTENDANCE_COVERAGE_LOW
                ? (() => {
                    const delayed = new Date(nowDate);
                    delayed.setUTCHours(delayed.getUTCHours() + 24); // Grace window before first attendance nag.
                    return delayed;
                  })()
                : nowDate,
            meta: c.meta,
          },
        });
    for (const userId of c.recipientUserIds) {
      await db.alertRecipientState.upsert({
        where: { alertEventId_userId: { alertEventId: event.id, userId } },
        create: { alertEventId: event.id, userId },
        update: {},
      });
    }
    if (hasMeaningfulChange) {
      await db.alertRecipientState.updateMany({
        where: { alertEventId: event.id },
        data: { emailedAt: null },
      });
    }
    const shouldAttemptDelivery =
      !existing ||
      hasMeaningfulChange ||
      Boolean(existing?.notifyAfter && existing.notifyAfter <= nowDate);
    if (shouldAttemptDelivery) {
      written.push({
        event,
        recipientUserIds: c.recipientUserIds,
        smtpEnabled: c.smtpEnabled,
        cooldownMinutes:
          c.type === ALERT_TYPES.DROPOUT_RISK_SUMMARY
            ? Math.max(c.cooldownMinutes, 7 * 24 * 60)
            : c.cooldownMinutes,
      });
    }
  }

  return {
    generatedAt: nowDate.toISOString(),
    generatedCount: written.length,
    candidates: written,
    adminUserIds,
  };
}
