import { lookup } from 'node:dns/promises';
import { isIP } from 'node:net';
import { OutboundError, getPublicJson, isPublicAddress, relaxedOutbound } from '../../lib/safeFetch';
import { BedStatus, Prisma, Role } from '@prisma/client';
import { db, prismaUnscoped } from '../../lib/prisma';
import { getTenantIdOrThrow, runWithTenantContext } from '../../lib/tenantContext';
import { BadRequestError, NotFoundError } from '../../lib/errors';
import { openSecret, sealSecret } from '../../lib/totp';
import { tenantHasFeature } from '../../middleware/requireFeature';
import { pushTo, staffWith } from '../notifications/notifications.service';
import { ingestReadings } from './energy.service';

/**
 * Energy KPIs (Sprint 4, TEPL): units used by room, floor and block for a
 * month; per occupied bed; month on month against occupancy; the day by day
 * curve; the top users. Readings are cumulative, so a meter's use over a
 * period is its last reading at the end less its last reading before the
 * start (or its first inside the period, for a meter fitted since).
 *
 * Also the high-use alerts (a room's day well over its usual) and the BMS
 * connector for pull mode, where we fetch readings rather than the BMS
 * pushing them.
 */

const IST_MS = 330 * 60_000;
const DAY = 86_400_000;
const round = (n: number, d = 1) => Math.round(n * 10 ** d) / 10 ** d;

/** Midnight in India at the start of a YYYY-MM-DD. */
const istStart = (ymd: string) => new Date(Date.parse(`${ymd}T00:00:00.000Z`) - IST_MS);
const istYmd = (t: number) => new Date(t + IST_MS).toISOString().slice(0, 10);
const monthStart = (ym: string) => istStart(`${ym}-01`);
const nextMonth = (ym: string) => {
  const [y, m] = ym.split('-').map(Number);
  return m === 12 ? `${y + 1}-01` : `${y}-${String(m + 1).padStart(2, '0')}`;
};
const prevMonth = (ym: string) => {
  const [y, m] = ym.split('-').map(Number);
  return m === 1 ? `${y - 1}-12` : `${y}-${String(m - 1).padStart(2, '0')}`;
};

/**
 * Each meter's last reading at or before `at`. Raw SQL for the lateral seek,
 * with the tenant stated explicitly (raw queries bypass the scoped client).
 */
async function lastAtOrBefore(tenantId: string, at: Date): Promise<Map<string, number>> {
  // One index seek per meter on (meterId, readAt): fast however long the history.
  const rows = await prismaUnscoped.$queryRaw<{ meterId: string; kwh: number }[]>(Prisma.sql`
    SELECT m."id" AS "meterId", r."kwh" FROM "EnergyMeter" m
    CROSS JOIN LATERAL (SELECT "kwh" FROM "MeterReading" WHERE "meterId" = m."id" AND "readAt" <= ${at} ORDER BY "readAt" DESC LIMIT 1) r
    WHERE m."tenantId" = ${tenantId}`);
  return new Map(rows.map((r) => [r.meterId, Number(r.kwh)]));
}

/** Each meter's first reading in [from, to] — the start for a meter fitted since `from`. */
async function firstWithin(tenantId: string, from: Date, to: Date): Promise<Map<string, number>> {
  const rows = await prismaUnscoped.$queryRaw<{ meterId: string; kwh: number }[]>(Prisma.sql`
    SELECT m."id" AS "meterId", r."kwh" FROM "EnergyMeter" m
    CROSS JOIN LATERAL (SELECT "kwh" FROM "MeterReading" WHERE "meterId" = m."id" AND "readAt" > ${from} AND "readAt" <= ${to} ORDER BY "readAt" ASC LIMIT 1) r
    WHERE m."tenantId" = ${tenantId}`);
  return new Map(rows.map((r) => [r.meterId, Number(r.kwh)]));
}

/** Units per meter between two moments (raw, before the multiplier). */
async function usage(tenantId: string, from: Date, to: Date) {
  const [start, end, fitted] = await Promise.all([lastAtOrBefore(tenantId, from), lastAtOrBefore(tenantId, to), firstWithin(tenantId, from, to)]);
  const out = new Map<string, number>();
  for (const [meterId, last] of end) {
    const first = start.get(meterId) ?? fitted.get(meterId);
    if (first === undefined) continue;
    // A meter swapped or reset reads lower: count nothing rather than a negative.
    out.set(meterId, Math.max(0, last - first));
  }
  return out;
}

/** Beds taken at a moment, per room: residents moved in by then and not yet gone. */
async function occupiedAt(at: Date) {
  const rows = await db.studentProfile.groupBy({
    by: ['bedId'],
    where: { bedId: { not: null }, movedInAt: { lte: at }, OR: [{ vacatedAt: null }, { vacatedAt: { gt: at } }] },
    _count: { _all: true },
  });
  const beds = await db.bed.findMany({ where: { id: { in: rows.map((r) => r.bedId!).filter(Boolean) } }, select: { id: true, roomId: true } });
  const roomOf = new Map(beds.map((b) => [b.id, b.roomId]));
  const perRoom = new Map<string, number>();
  for (const r of rows) {
    const room = roomOf.get(r.bedId!);
    if (room) perRoom.set(room, (perRoom.get(room) ?? 0) + 1);
  }
  return perRoom;
}

export async function kpis(month: string, propertyId?: string) {
  if (!/^\d{4}-\d{2}$/.test(month)) throw new BadRequestError('month must be YYYY-MM');
  const tenantId = getTenantIdOrThrow();
  const from = monthStart(month);
  const end = new Date(Math.min(monthStart(nextMonth(month)).getTime(), Date.now()));
  if (end <= from) throw new BadRequestError('That month has not started');

  const [meters, properties, rooms] = await Promise.all([
    db.energyMeter.findMany({ where: { ...(propertyId ? { propertyId } : {}) }, select: { id: true, code: true, name: true, kind: true, roomId: true, propertyId: true, multiplier: true, isActive: true } }),
    db.property.findMany({ where: propertyId ? { id: propertyId } : {}, select: { id: true, name: true } }),
    db.room.findMany({ where: { archivedAt: null, ...(propertyId ? { propertyId } : {}) }, select: { id: true, number: true, floor: true, propertyId: true, beds: { select: { status: true } } } }),
  ]);
  const used = await usage(tenantId, from, end);
  const occupiedNow = await occupiedAt(end);
  const blockName = new Map(properties.map((p) => [p.id, p.name]));
  const roomById = new Map(rooms.map((r) => [r.id, r]));
  const units = (m: (typeof meters)[number]) => (used.get(m.id) ?? 0) * m.multiplier;

  // Rooms.
  const roomRows = meters
    .filter((m) => m.kind === 'ROOM' && m.roomId && roomById.has(m.roomId))
    .map((m) => {
      const r = roomById.get(m.roomId!)!;
      const kwh = units(m);
      const occupied = occupiedNow.get(r.id) ?? r.beds.filter((b) => b.status === BedStatus.OCCUPIED).length;
      return { roomId: r.id, number: r.number, floor: r.floor, propertyId: r.propertyId, block: blockName.get(r.propertyId) ?? null, meter: m.code, kwh: round(kwh), beds: r.beds.length, occupied, perOccupiedBed: occupied ? round(kwh / occupied) : null, reading: used.has(m.id) };
    })
    .sort((a, b) => b.kwh - a.kwh);

  // Floors and blocks (common meters count to their block, not a floor).
  const floors = new Map<string, { propertyId: string; block: string | null; floor: number | null; kwh: number; rooms: number; occupied: number }>();
  for (const r of roomRows) {
    const key = `${r.propertyId}:${r.floor ?? ''}`;
    const f = floors.get(key) ?? { propertyId: r.propertyId, block: r.block, floor: r.floor, kwh: 0, rooms: 0, occupied: 0 };
    f.kwh += r.kwh;
    f.rooms++;
    f.occupied += r.occupied;
    floors.set(key, f);
  }
  const blocks = properties.map((p) => {
    const mine = meters.filter((m) => m.propertyId === p.id);
    const roomKwh = mine.filter((m) => m.kind === 'ROOM').reduce((n, m) => n + units(m), 0);
    const commonKwh = mine.filter((m) => m.kind === 'COMMON').reduce((n, m) => n + units(m), 0);
    // Every room's beds count, metered or not, so occupancy is the block's own.
    const occupied = rooms.filter((r) => r.propertyId === p.id).reduce((n, r) => n + (occupiedNow.get(r.id) ?? r.beds.filter((b) => b.status === BedStatus.OCCUPIED).length), 0);
    const beds = rooms.filter((r) => r.propertyId === p.id).reduce((n, r) => n + r.beds.length, 0);
    return { propertyId: p.id, block: p.name, kwh: round(roomKwh + commonKwh), roomKwh: round(roomKwh), commonKwh: round(commonKwh), occupied, beds, occupancy: beds ? round((occupied / beds) * 100, 0) : null, perOccupiedBed: occupied ? round((roomKwh + commonKwh) / occupied) : null, meters: mine.length };
  });

  // Month on month: the six months to this one, each with its occupancy at month end.
  const months: { month: string; kwh: number; occupied: number; perOccupiedBed: number | null }[] = [];
  let ym = month;
  const series: string[] = [];
  for (let i = 0; i < 6; i++) {
    series.unshift(ym);
    ym = prevMonth(ym);
  }
  const meterIds = new Set(meters.map((m) => m.id));
  const mult = new Map(meters.map((m) => [m.id, m.multiplier]));
  for (const m of series) {
    const a = monthStart(m);
    const b = new Date(Math.min(monthStart(nextMonth(m)).getTime(), Date.now()));
    if (b <= a) continue;
    const u = await usage(tenantId, a, b);
    const kwh = [...u.entries()].filter(([id]) => meterIds.has(id)).reduce((n, [id, v]) => n + v * (mult.get(id) ?? 1), 0);
    const occ = [...(await occupiedAt(b)).entries()].filter(([roomId]) => roomById.has(roomId)).reduce((n, [, c]) => n + c, 0);
    months.push({ month: m, kwh: round(kwh), occupied: occ, perOccupiedBed: occ ? round(kwh / occ) : null });
  }

  // Day by day this month, per block.
  const days: { day: string; kwh: number; byBlock: Record<string, number> }[] = [];
  for (let t = from.getTime(); t < end.getTime(); t += DAY) {
    const a = new Date(t);
    const b = new Date(Math.min(t + DAY, end.getTime()));
    const u = await usage(tenantId, a, b);
    const byBlock: Record<string, number> = {};
    let total = 0;
    for (const m of meters) {
      const v = (u.get(m.id) ?? 0) * m.multiplier;
      byBlock[m.propertyId] = round((byBlock[m.propertyId] ?? 0) + v);
      total += v;
    }
    days.push({ day: istYmd(t), kwh: round(total), byBlock });
  }

  const totalKwh = blocks.reduce((n, b) => n + b.kwh, 0);
  const occupied = blocks.reduce((n, b) => n + b.occupied, 0);
  const elapsedDays = Math.max(1, (end.getTime() - from.getTime()) / DAY);
  return {
    month,
    from,
    to: end,
    totals: { kwh: round(totalKwh), perOccupiedBed: occupied ? round(totalKwh / occupied) : null, perDay: round(totalKwh / elapsedDays), occupied, meters: meters.length, roomsWithoutReading: roomRows.filter((r) => !r.reading).length },
    blocks,
    floors: [...floors.values()].map((f) => ({ ...f, kwh: round(f.kwh), perOccupiedBed: f.occupied ? round(f.kwh / f.occupied) : null })).sort((a, b) => (a.block ?? '').localeCompare(b.block ?? '') || (a.floor ?? 0) - (b.floor ?? 0)),
    rooms: roomRows,
    top: roomRows.filter((r) => r.perOccupiedBed !== null).sort((a, b) => b.perOccupiedBed! - a.perOccupiedBed!).slice(0, 10),
    months,
    days,
  };
}

// ── High-use alerts ─────────────────────────────────────────────────────────

const median = (xs: number[]) => {
  const s = [...xs].sort((a, b) => a - b);
  return s.length ? (s.length % 2 ? s[(s.length - 1) / 2] : (s[s.length / 2 - 1] + s[s.length / 2]) / 2) : 0;
};

/**
 * One account's yesterday (India date): each room meter's day against the
 * median of its fourteen days before. Over the ratio and the floor in units
 * → one alert per meter per day.
 */
export async function checkHighUse(day: string) {
  const tenantId = getTenantIdOrThrow();
  const setting = await db.energySetting.findFirst({ select: { alertRatio: true, alertMinKwh: true } });
  const ratio = setting?.alertRatio ?? 1.5;
  const floor = setting?.alertMinKwh ?? 3;
  const meters = await db.energyMeter.findMany({ where: { isActive: true, kind: 'ROOM' }, select: { id: true, propertyId: true, multiplier: true } });
  if (!meters.length) return [];
  const bounds: Date[] = [];
  for (let i = 15; i >= 0; i--) bounds.push(new Date(istStart(day).getTime() - (i - 1) * DAY));
  // bounds[k]..bounds[k+1] is one day; the last pair is `day` itself.
  const readings = await Promise.all(bounds.map((b) => lastAtOrBefore(tenantId, b)));
  const fresh: { meterId: string; propertyId: string; kwh: number; baseline: number }[] = [];
  for (const m of meters) {
    const daily: number[] = [];
    for (let k = 0; k < bounds.length - 1; k++) {
      const a = readings[k].get(m.id);
      const b = readings[k + 1].get(m.id);
      daily.push(a !== undefined && b !== undefined ? Math.max(0, b - a) * m.multiplier : NaN);
    }
    const today = daily.at(-1)!;
    const past = daily.slice(0, -1).filter((x) => Number.isFinite(x) && x > 0);
    if (!Number.isFinite(today) || past.length < 5) continue;
    const baseline = median(past);
    if (today >= floor && today > baseline * ratio) fresh.push({ meterId: m.id, propertyId: m.propertyId, kwh: round(today, 2), baseline: round(baseline, 2) });
  }
  if (!fresh.length) return [];
  // This runs hourly: only meters without an alert for the day are new.
  const date = new Date(`${day}T00:00:00.000Z`);
  const known = new Set((await db.energyAlert.findMany({ where: { date, meterId: { in: fresh.map((f) => f.meterId) } }, select: { meterId: true } })).map((a) => a.meterId));
  const made = fresh.filter((f) => !known.has(f.meterId));
  if (made.length) await db.energyAlert.createMany({ data: made.map((f) => ({ tenantId, ...f, date })), skipDuplicates: true });
  return made;
}

/** Hourly, from 1 am India time: yesterday's check, once per account (the alerts are unique per meter and day). */
export async function runEnergyPass(now = new Date()) {
  const tenants = await prismaUnscoped.tenant.findMany({ where: { status: 'ACTIVE', kind: 'ENTERPRISE' }, select: { id: true } });
  const hourIst = new Date(now.getTime() + IST_MS).getUTCHours();
  for (const t of tenants) {
    if (!(await tenantHasFeature(t.id, 'energy'))) continue;
    await runWithTenantContext({ tenantId: t.id, userId: 'system', role: Role.HOSTEL_ADMIN }, async () => {
      await pullFromBms().catch((err) => console.error('[energy] BMS pull failed:', err)); // eslint-disable-line no-console
      if (hourIst < 1) return;
      const yesterday = istYmd(now.getTime() - DAY);
      const made = await checkHighUse(yesterday);
      if (made.length) {
        const staff = await staffWith(t.id, 'MANAGE_PROPERTY');
        await pushTo(t.id, 'ENERGY_HIGH_USE', `energy:${yesterday}`, staff, {
          title: `High energy use in ${made.length} room${made.length === 1 ? '' : 's'}`,
          body: `Yesterday (${yesterday}) ${made.length === 1 ? 'one room' : `${made.length} rooms`} used well over their usual. See Energy → Alerts.`,
          data: { day: yesterday },
        });
      }
    });
  }
}

export async function listAlerts(status: 'OPEN' | 'ACKNOWLEDGED' | undefined, propertyId?: string) {
  const rows = await db.energyAlert.findMany({ where: { ...(status ? { status } : {}), ...(propertyId ? { propertyId } : {}) }, orderBy: [{ date: 'desc' }, { kwh: 'desc' }], take: 300 });
  const meters = await db.energyMeter.findMany({ where: { id: { in: rows.map((r) => r.meterId) } }, select: { id: true, code: true, name: true, roomId: true } });
  const rooms = await db.room.findMany({ where: { id: { in: meters.map((m) => m.roomId).filter((x): x is string => !!x) } }, select: { id: true, number: true } });
  const meterOf = new Map(meters.map((m) => [m.id, m]));
  const roomNo = new Map(rooms.map((r) => [r.id, r.number]));
  return rows.map((r) => {
    const m = meterOf.get(r.meterId);
    return { ...r, meter: m?.code ?? null, meterName: m?.name ?? null, room: m?.roomId ? roomNo.get(m.roomId) ?? null : null, times: r.baseline ? round(r.kwh / r.baseline) : null };
  });
}

export async function ackAlert(id: string, actorId: string) {
  const a = await db.energyAlert.findFirst({ where: { id } });
  if (!a) throw new NotFoundError('Alert not found');
  return db.energyAlert.update({ where: { id }, data: { status: 'ACKNOWLEDGED', ackedById: actorId, ackedAt: new Date() } });
}

// ── Settings and the BMS connector (pull mode) ──────────────────────────────

const publicSetting = (s: { bmsPullUrl: string | null; bmsTokenSealed: string | null; lastPulledAt: Date | null; lastPullError: string | null; alertRatio: number; alertMinKwh: number } | null) => ({
  bmsPullUrl: s?.bmsPullUrl ?? null,
  hasToken: !!s?.bmsTokenSealed,
  lastPulledAt: s?.lastPulledAt ?? null,
  lastPullError: s?.lastPullError ?? null,
  alertRatio: s?.alertRatio ?? 1.5,
  alertMinKwh: s?.alertMinKwh ?? 3,
});

export async function getSettings() {
  return publicSetting(await db.energySetting.findFirst());
}

/**
 * The pull address must be https to a public host, so the server cannot be
 * pointed at itself or the private network (checked again, on the resolved
 * address, when it connects — see lib/safeFetch). Only while developing or
 * testing are plain http and private hosts allowed, for the simulator.
 */
export async function checkPullUrl(raw: string) {
  let url: URL;
  try {
    url = new URL(raw);
  } catch {
    throw new BadRequestError('That is not a web address');
  }
  const relaxed = relaxedOutbound();
  if (url.protocol !== 'https:' && !(relaxed && url.protocol === 'http:')) throw new BadRequestError('The BMS address must start with https://');
  if (url.username || url.password) throw new BadRequestError('Put the key in the token field, not in the address');
  if (!relaxed) {
    const host = url.hostname.replace(/^\[|\]$/g, '');
    const addrs = isIP(host) ? [host] : (await lookup(host, { all: true }).catch(() => [])).map((a) => a.address);
    if (!addrs.length) throw new BadRequestError('That address does not resolve');
    if (host === 'localhost' || addrs.some((a) => !isPublicAddress(a))) throw new BadRequestError('The BMS address must be reachable on the internet; a BMS inside the plant network should push its readings instead');
  }
  return url;
}

export async function saveSettings(input: { bmsPullUrl?: string | null; bmsToken?: string | null; alertRatio?: number; alertMinKwh?: number }) {
  const tenantId = getTenantIdOrThrow();
  if (input.bmsPullUrl) await checkPullUrl(input.bmsPullUrl);
  const data = {
    ...(input.bmsPullUrl !== undefined ? { bmsPullUrl: input.bmsPullUrl || null } : {}),
    ...(input.bmsToken !== undefined ? { bmsTokenSealed: input.bmsToken ? sealSecret(input.bmsToken) : null } : {}),
    ...(input.alertRatio !== undefined ? { alertRatio: input.alertRatio } : {}),
    ...(input.alertMinKwh !== undefined ? { alertMinKwh: input.alertMinKwh } : {}),
  };
  const existing = await db.energySetting.findFirst({ select: { id: true } });
  const s = existing ? await db.energySetting.update({ where: { id: existing.id }, data }) : await db.energySetting.create({ data: { tenantId, ...data } });
  return publicSetting(s);
}

/**
 * Pull mode: GET {bmsPullUrl}?since=ISO with the token as a bearer, answered
 * with { readings: [{ meter, readAt, kwh }] } — the same shape the BMS would
 * push. Nothing configured, nothing done.
 */
export async function pullFromBms() {
  const s = await db.energySetting.findFirst();
  if (!s?.bmsPullUrl) return null;
  const since = s.lastPulledAt ?? new Date(Date.now() - 2 * 3_600_000);
  const started = new Date();
  try {
    const url = await checkPullUrl(s.bmsPullUrl);
    url.searchParams.set('since', since.toISOString());
    const body = (await getPublicJson(url, { headers: s.bmsTokenSealed ? { Authorization: `Bearer ${openSecret(s.bmsTokenSealed)}` } : {}, timeoutMs: 20_000 })) as { readings?: unknown } | null;
    if (!body || !Array.isArray(body.readings)) throw new OutboundError('The BMS answer has no readings list');
    const readings = body.readings
      .slice(0, 20_000)
      .filter((r): r is { meter: string; readAt: string; kwh: number } => !!r && typeof r === 'object' && typeof (r as { meter?: unknown }).meter === 'string' && typeof (r as { readAt?: unknown }).readAt === 'string' && typeof (r as { kwh?: unknown }).kwh === 'number');
    const result = readings.length ? await ingestReadings(readings, 'BMS') : { received: 0, accepted: 0, duplicates: 0, invalid: 0, unknownMeters: [] as string[] };
    await db.energySetting.update({ where: { id: s.id }, data: { lastPulledAt: started, lastPullError: null } });
    return result;
  } catch (e) {
    // Only our own words are kept and shown — never what the far end sent back.
    const message = e instanceof OutboundError || e instanceof BadRequestError ? e.message.slice(0, 200) : 'The pull failed';
    await db.energySetting.update({ where: { id: s.id }, data: { lastPullError: message } });
    throw new BadRequestError(message);
  }
}
