import { StudentRequestStatus, StudentRequestType } from '@prisma/client';
import { db } from '../../lib/prisma';
import { getTenantIdOrThrow } from '../../lib/tenantContext';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { adherence } from '../roster/roster-adherence';
import { summary as feedbackSummary } from '../feedback/feedback.service';
import { grievanceSummary } from '../requests/grievance.service';
import { kpis as energyKpis } from '../energy/energy-kpi.service';
import { consumption } from '../canteen/canteen.service';

/**
 * The leadership view (Sprint 6, TEPL): one page for the plant's management,
 * each block side by side and both together. Occupancy and its history,
 * leave, shift adherence, satisfaction and grievances, energy per occupied
 * bed, canteen turn-out, and safety. Each part reads the module that owns
 * it, and a part whose module is off is left out (null).
 */

const IST_MS = 330 * 60_000;
const DAY = 86_400_000;
const istYmd = (t: number) => new Date(t + IST_MS).toISOString().slice(0, 10);
const round = (n: number, d = 1) => Math.round(n * 10 ** d) / 10 ** d;
const pct = (a: number, b: number) => (b ? Math.round((a / b) * 100) : null);

/** The last `n` India months, oldest first, with their end moments (now, for this month). */
function monthsBack(n: number) {
  const now = new Date(Date.now() + IST_MS);
  const out: { month: string; start: Date; end: Date }[] = [];
  for (let i = n - 1; i >= 0; i--) {
    const y = now.getUTCFullYear();
    const m = now.getUTCMonth() - i;
    const start = new Date(Date.UTC(y, m, 1) - IST_MS);
    const next = new Date(Date.UTC(y, m + 1, 1) - IST_MS);
    out.push({ month: new Date(Date.UTC(y, m, 1)).toISOString().slice(0, 7), start, end: new Date(Math.min(next.getTime(), Date.now())) });
  }
  return out;
}

async function block(propertyId: string | undefined, months: ReturnType<typeof monthsBack>, on: Record<string, boolean>) {
  const scope = propertyId ? { propertyId } : {};
  const beds = await db.bed.count({ where: { archivedAt: null, room: { archivedAt: null, ...scope } } });
  const occupiedAt = (at: Date) => db.studentProfile.count({ where: { ...scope, bedId: { not: null }, movedInAt: { lte: at }, OR: [{ vacatedAt: null }, { vacatedAt: { gt: at } }] } });
  const occupancy = await Promise.all(months.map(async (m) => {
    const occ = await occupiedAt(m.end);
    return { month: m.month, occupied: occ, rate: pct(occ, beds) };
  }));
  const occupiedNow = await db.studentProfile.count({ where: { ...scope, bedId: { not: null }, residencyStatus: { not: 'VACATED' } } });

  // Leave: approved leave-days by the month they start, and how many wait now.
  const since = months[0].start;
  const leaves = on.leavePolicy
    ? await db.studentRequest.findMany({ where: { type: StudentRequestType.LEAVE, status: StudentRequestStatus.APPROVED, fromDate: { gte: since }, ...(propertyId ? { student: { propertyId } } : {}) }, select: { fromDate: true, leaveDays: true } })
    : [];
  const pendingLeave = on.leavePolicy ? await db.studentRequest.count({ where: { type: StudentRequestType.LEAVE, status: { in: [StudentRequestStatus.OPEN, StudentRequestStatus.IN_PROGRESS] }, ...(propertyId ? { student: { propertyId } } : {}) } }) : 0;
  const leave = on.leavePolicy
    ? { pending: pendingLeave, months: months.map((m) => ({ month: m.month, days: round(leaves.filter((l) => l.fromDate && l.fromDate >= m.start && l.fromDate < m.end).reduce((n, l) => n + (l.leaveDays ?? 1), 0)) })) }
    : null;

  // Shift adherence: today's, and the last seven days' flagged share.
  let attendance: { today: { rostered: number; onTime: number; flagged: number }; week: { day: string; rostered: number; flagged: number; rate: number | null }[] } | null = null;
  if (on.shiftRoster) {
    const week: { day: string; rostered: number; flagged: number; rate: number | null }[] = [];
    for (let d = 6; d >= 0; d--) {
      const day = istYmd(Date.now() - d * DAY);
      const a = await adherence(day, propertyId ? { propertyId } : {});
      week.push({ day, rostered: a.summary.rostered, flagged: a.summary.flagged, rate: pct(a.summary.onTime, a.summary.onTime + a.summary.late + a.summary.noSwipeOut) });
    }
    const t = await adherence(istYmd(Date.now()), propertyId ? { propertyId } : {});
    attendance = { today: { rostered: t.summary.rostered, onTime: t.summary.onTime, flagged: t.summary.flagged }, week };
  }

  const satisfaction = on.feedback ? (await feedbackSummary(months.length, propertyId)).months.map((m) => ({ month: m.period, responses: m.responses, overall: m.overall })) : null;
  const g = on.grievanceDesk ? await grievanceSummary(30, propertyId) : null;
  const grievances = g ? { raised: g.overall.raised, open: g.overall.open, withinTarget: g.overall.withinTarget, avgRating: g.overall.avgRating, escalated: g.overall.escalated, top: g.byCategory.slice(0, 3).map((c) => ({ category: c.category, raised: c.raised })) } : null;

  // Energy per occupied bed, month by month, from the energy dashboard.
  let energy: { months: { month: string; kwh: number; perOccupiedBed: number | null }[] } | null = null;
  if (on.energy && (await db.energyMeter.count({ where: scope })) > 0) {
    const k = await energyKpis(months[months.length - 1].month, propertyId);
    energy = { months: k.months.map((m) => ({ month: m.month, kwh: m.kwh, perOccupiedBed: m.perOccupiedBed })) };
  }

  // Canteen: the last seven days' turn-out per meal.
  let canteen: { meals: { meal: string; served: number; expected: number; rate: number | null }[] } | null = null;
  if (on.canteen) {
    const c = await consumption(istYmd(Date.now() - 6 * DAY), istYmd(Date.now()), propertyId);
    canteen = { meals: c.totals };
  }

  // Safety.
  const since30 = new Date(Date.now() - 30 * DAY);
  const safety = {
    openAlerts: on.emergency ? await db.emergencyAlert.count({ where: { closedAt: null, ...(propertyId ? { OR: [{ propertyId }, { propertyId: null }] } : {}) } }) : null,
    lastDrill: on.emergency ? (await db.emergencyAlert.findFirst({ where: { isDrill: true, ...(propertyId ? { OR: [{ propertyId }, { propertyId: null }] } : {}) }, orderBy: { raisedAt: 'desc' }, select: { raisedAt: true } }))?.raisedAt ?? null : null,
    curfewBreaches30: on.quickOutings ? await db.curfewBreach.count({ where: { ...scope, createdAt: { gte: since30 } } }) : null,
    incidents30: on.discipline ? await db.disciplineIncident.count({ where: { occurredAt: { gte: since30 }, ...(propertyId ? { student: { propertyId } } : {}) } }) : null,
    trainingLapsed: on.emergency ? await db.emergencyTeamMember.count({ where: { isActive: true, validUntil: { lt: new Date() }, ...(propertyId ? { OR: [{ propertyId }, { propertyId: null }] } : {}) } }) : null,
  };

  return { beds, occupiedNow, occupancyNow: pct(occupiedNow, beds), occupancy, leave, attendance, satisfaction, grievances, energy, canteen, safety };
}

export async function overview(monthCount = 6) {
  const tenantId = getTenantIdOrThrow();
  const keys = ['leavePolicy', 'shiftRoster', 'feedback', 'grievanceDesk', 'energy', 'canteen', 'emergency', 'quickOutings', 'discipline'] as const;
  const on = Object.fromEntries(await Promise.all(keys.map(async (k) => [k, await tenantHasFeature(tenantId, k)] as const))) as Record<string, boolean>;
  const months = monthsBack(monthCount);
  const properties = await db.property.findMany({ where: { isArchived: false }, select: { id: true, name: true }, orderBy: { name: 'asc' } });
  const blocks = await Promise.all(properties.map(async (p) => ({ propertyId: p.id, name: p.name, ...(await block(p.id, months, on)) })));
  const combined = await block(undefined, months, on);
  return { generatedAt: new Date(), months: months.map((m) => m.month), blocks, combined };
}
