import { BugSeverity, BugStatus, Role, type Prisma } from '@prisma/client';
import { prismaUnscoped as db } from '../../lib/prisma';
import { isPlaceholderEmail } from '../../lib/no-login';
import { crmEmail } from '../../lib/email-templates';
import { writeXlsx, type Cell } from '../../lib/xlsx';
import { publicWebUrl } from '../../config/env';
import type { BugActor } from './bug-access';
import { orderOf, whereOf } from './bug-bugs.service';
import { bugUrl, mail, resolutionLabel } from './bug-notify.service';
import { bugKey, type ListBugsInput } from './bug-rules';

/**
 * The numbers (docs/bug-tracker-plan.md, BT4): the dashboard, the Excel export
 * of the bug list, and the super admin's Monday summary.
 *
 * "Open" here means not closed: a bug waiting for QA is still open until QA
 * closes it. Weeks start on Monday, India time.
 */

const DAY = 86_400_000;
const IST_MS = 330 * 60_000;
const NOT_CLOSED: BugStatus[] = [BugStatus.OPEN, BugStatus.IN_PROGRESS, BugStatus.NEEDS_INFO, BugStatus.REOPENED, BugStatus.FIXED];
const NEEDS_DEVELOPER: BugStatus[] = [BugStatus.OPEN, BugStatus.IN_PROGRESS, BugStatus.REOPENED];
const SEVERITIES = Object.values(BugSeverity);
const WEEKS = 8;
/** How far back the fix and verify times look. */
const QUALITY_DAYS = 90;

const csv = (l: readonly string[]) => l.join(',');
const istDate = (d: Date) => new Date(d.getTime() + IST_MS).toISOString().slice(0, 10);

/** The instant this week began: Monday 00:00, India time. */
export function weekStart(now: Date): Date {
  const shifted = new Date(now.getTime() + IST_MS);
  const sinceMonday = (shifted.getUTCDay() + 6) % 7;
  return new Date(Date.UTC(shifted.getUTCFullYear(), shifted.getUTCMonth(), shifted.getUTCDate() - sinceMonday) - IST_MS);
}

interface Tile {
  key: string;
  label: string;
  count: number;
  /** The same bugs on the bug list. */
  filters: Record<string, string>;
}

async function tiles(now: Date): Promise<Tile[]> {
  const open = { status: { in: NOT_CLOSED } } satisfies Prisma.BugWhereInput;
  const specs: (Omit<Tile, 'count'> & { where: Prisma.BugWhereInput })[] = [
    { key: 'open', label: 'Open', filters: { status: csv(NOT_CLOSED) }, where: open },
    { key: 'unassigned', label: 'Unassigned', filters: { assigneeId: 'none', status: csv(NEEDS_DEVELOPER) }, where: { assigneeId: null, status: { in: NEEDS_DEVELOPER } } },
    { key: 'waiting-for-qa', label: 'Waiting for QA', filters: { status: 'FIXED' }, where: { status: BugStatus.FIXED } },
    { key: 'reopened', label: 'Reopened', filters: { status: 'REOPENED' }, where: { status: BugStatus.REOPENED } },
    { key: 'critical', label: 'Critical, open', filters: { severity: 'CRITICAL', status: csv(NOT_CLOSED) }, where: { ...open, severity: BugSeverity.CRITICAL } },
    { key: 'older-7', label: 'Open over 7 days', filters: { olderThan: '7', status: csv(NOT_CLOSED), sort: 'oldest' }, where: { ...open, createdAt: { lt: new Date(now.getTime() - 7 * DAY) } } },
    { key: 'older-30', label: 'Open over 30 days', filters: { olderThan: '30', status: csv(NOT_CLOSED), sort: 'oldest' }, where: { ...open, createdAt: { lt: new Date(now.getTime() - 30 * DAY) } } },
  ];
  const counts = await Promise.all(specs.map((s) => db.bug.count({ where: s.where })));
  return specs.map(({ where: _where, ...t }, i) => ({ ...t, count: counts[i] }));
}

/** Opened and closed, week by week, oldest first. A bug reopened since no longer counts as closed. */
async function weeks(now: Date, n = WEEKS) {
  const thisWeek = weekStart(now).getTime();
  const from = new Date(thisWeek - (n - 1) * 7 * DAY);
  const [opened, closed] = await Promise.all([
    db.bug.findMany({ where: { createdAt: { gte: from } }, select: { createdAt: true } }),
    db.bug.findMany({ where: { status: BugStatus.CLOSED, closedAt: { gte: from } }, select: { closedAt: true } }),
  ]);
  const out = Array.from({ length: n }, (_, i) => ({ start: istDate(new Date(from.getTime() + i * 7 * DAY)), opened: 0, closed: 0 }));
  const slot = (d: Date) => Math.min(n - 1, Math.floor((d.getTime() - from.getTime()) / (7 * DAY)));
  for (const b of opened) out[slot(b.createdAt)].opened++;
  for (const b of closed) if (b.closedAt) out[slot(b.closedAt)].closed++;
  return out;
}

interface Walk {
  /** Bugs a fix was reported for. */
  fixed: Set<string>;
  /** Of those, the ones QA sent back. */
  sentBack: Set<string>;
  fixHours: number[];
  verifyHours: number[];
  /** Per developer: bugs fixed, and fixes sent back. */
  byDeveloper: Map<string, { fixed: Set<string>; sentBack: Set<string> }>;
}

/**
 * Read the moves since `from` in order: how long fixes took (from the report,
 * or from the last reopen, to "fixed"), how long QA took to verify them, and
 * which fixes were sent back.
 */
async function walk(from: Date): Promise<Walk> {
  const events = await db.bugEvent.findMany({
    where: { type: 'STATUS', createdAt: { gte: from } },
    select: { bugId: true, actorId: true, createdAt: true, changes: true, bug: { select: { createdAt: true } } },
    orderBy: { createdAt: 'asc' },
    take: 20_000,
  });
  const w: Walk = { fixed: new Set(), sentBack: new Set(), fixHours: [], verifyHours: [], byDeveloper: new Map() };
  const state = new Map<string, { since: number; fixedAt: number | null; fixedBy: string | null }>();
  const dev = (id: string) => w.byDeveloper.get(id) ?? w.byDeveloper.set(id, { fixed: new Set(), sentBack: new Set() }).get(id)!;
  for (const e of events) {
    const c = (e.changes ?? {}) as { action?: string; resolution?: string };
    const t = e.createdAt.getTime();
    const s = state.get(e.bugId) ?? state.set(e.bugId, { since: e.bug.createdAt.getTime(), fixedAt: null, fixedBy: null }).get(e.bugId)!;
    if (c.action === 'fix') {
      w.fixed.add(e.bugId);
      w.fixHours.push((t - s.since) / 3_600_000);
      dev(e.actorId).fixed.add(e.bugId);
      s.fixedAt = t;
      s.fixedBy = e.actorId;
    } else if (c.action === 'reopen') {
      if (s.fixedAt !== null) {
        w.sentBack.add(e.bugId);
        if (s.fixedBy) dev(s.fixedBy).sentBack.add(e.bugId);
      }
      s.since = t;
      s.fixedAt = null;
    } else if (c.action === 'close') {
      if (c.resolution === 'VERIFIED' && s.fixedAt !== null) w.verifyHours.push((t - s.fixedAt) / 3_600_000);
      s.fixedAt = null;
    } else if (c.action === 'suggest') {
      s.fixedAt = null;
    }
  }
  return w;
}

const average = (l: number[]) => (l.length ? Math.round((l.reduce((a, b) => a + b, 0) / l.length) * 10) / 10 : null);

async function developers(w: Walk) {
  const [people, load] = await Promise.all([
    db.user.findMany({ where: { role: Role.DEVELOPER }, select: { id: true, name: true, deactivatedAt: true }, orderBy: { name: 'asc' } }),
    db.bug.groupBy({ by: ['assigneeId', 'status'], where: { status: { in: NOT_CLOSED }, assigneeId: { not: null } }, _count: { _all: true } }),
  ]);
  const of = (id: string, statuses: BugStatus[]) => load.filter((l) => l.assigneeId === id && statuses.includes(l.status)).reduce((n, l) => n + l._count._all, 0);
  return people
    .map((p) => ({
      id: p.id,
      name: p.name,
      active: !p.deactivatedAt,
      toFix: of(p.id, [BugStatus.OPEN, BugStatus.IN_PROGRESS, BugStatus.NEEDS_INFO]),
      reopened: of(p.id, [BugStatus.REOPENED]),
      waitingForQa: of(p.id, [BugStatus.FIXED]),
      fixed: w.byDeveloper.get(p.id)?.fixed.size ?? 0,
      sentBack: w.byDeveloper.get(p.id)?.sentBack.size ?? 0,
    }))
    // Someone whose account is off stays on the list only while bugs are still theirs.
    .filter((d) => d.active || d.toFix + d.reopened + d.waitingForQa > 0);
}

/**
 * The dashboard. Everyone on the tracker sees where the bugs stand; the super
 * admin also sees how each developer is doing and how well fixes hold.
 */
export async function dashboard(actor: BugActor, now = new Date()) {
  const full = actor.role === Role.SUPER_ADMIN;
  const open = { status: { in: NOT_CLOSED } } satisfies Prisma.BugWhereInput;
  const [t, severity, byModule, modules, trend, w] = await Promise.all([
    tiles(now),
    db.bug.groupBy({ by: ['severity'], where: open, _count: { _all: true } }),
    db.bug.groupBy({ by: ['moduleId'], where: open, _count: { _all: true } }),
    db.bugModule.findMany({ select: { id: true, name: true } }),
    weeks(now),
    full ? walk(new Date(now.getTime() - QUALITY_DAYS * DAY)) : Promise.resolve(null),
  ]);
  const moduleName = new Map(modules.map((m) => [m.id, m.name]));
  return {
    full,
    tiles: t,
    bySeverity: SEVERITIES.map((s) => ({ severity: s, count: severity.find((x) => x.severity === s)?._count._all ?? 0, filters: { severity: s, status: csv(NOT_CLOSED) } })),
    byModule: byModule
      .map((m) => ({ id: m.moduleId, name: moduleName.get(m.moduleId) ?? 'Unknown', count: m._count._all, filters: { moduleId: m.moduleId, status: csv(NOT_CLOSED) } }))
      .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name))
      .slice(0, 12),
    weeks: trend,
    ...(w
      ? {
          developers: await developers(w),
          quality: {
            days: QUALITY_DAYS,
            fixed: w.fixed.size,
            sentBack: w.sentBack.size,
            /** Of the bugs fixed in the period, the share QA reopened. */
            reopenRate: w.fixed.size ? Math.round((w.sentBack.size / w.fixed.size) * 1000) / 1000 : null,
            avgFixHours: average(w.fixHours),
            avgVerifyHours: average(w.verifyHours),
          },
        }
      : {}),
  };
}

// ── Excel ───────────────────────────────────────────────────────────────────

const EXPORT_MAX = 5000;
const words = (v: string) => v.charAt(0) + v.slice(1).toLowerCase().replace(/_/g, ' ');

/** The bug list, as filtered and sorted on screen, as an .xlsx (the first 5,000). */
export async function exportBugs(f: ListBugsInput, now = new Date()) {
  const rows = await db.bug.findMany({ where: whereOf(f), include: { module: { select: { name: true } } }, orderBy: orderOf(f.sort), take: EXPORT_MAX });
  const ids = [...new Set(rows.flatMap((r) => [r.reporterId, r.assigneeId]).filter((v): v is string => !!v))];
  const who = new Map((await db.user.findMany({ where: { id: { in: ids } }, select: { id: true, name: true } })).map((u) => [u.id, u.name]));
  const data: Cell[][] = rows.map((b) => [
    bugKey(b.number),
    words(b.type),
    b.title,
    words(b.status === 'FIXED' ? 'WAITING_FOR_QA' : b.status),
    b.resolution ? resolutionLabel(b.resolution) + (b.status === 'FIXED' ? ' (suggested)' : '') : '',
    words(b.severity),
    b.priority ?? '',
    words(b.app),
    b.module.name,
    words(b.environment),
    b.tenantKind === 'ALL' ? 'All' : words(b.tenantKind),
    who.get(b.reporterId) ?? '',
    b.assigneeId ? (who.get(b.assigneeId) ?? '') : '',
    b.createdAt,
    b.lastActivityAt,
    b.closedAt,
    b.reopenCount,
    b.fixedIn ?? '',
    b.fixLink ?? '',
    b.steps,
    b.expected ?? '',
    b.actual ?? '',
    bugUrl(b.number),
  ]);
  const bytes = writeXlsx([
    {
      name: 'Bugs',
      columns: [
        { header: 'Bug', width: 10 },
        { header: 'Type', width: 12 },
        { header: 'Title', width: 50 },
        { header: 'Status', width: 18 },
        { header: 'Reason', width: 22 },
        { header: 'Severity', width: 10 },
        { header: 'Priority', width: 9 },
        { header: 'App', width: 13 },
        { header: 'Module', width: 22 },
        { header: 'Environment', width: 13 },
        { header: 'Hostel type', width: 13 },
        { header: 'Reported by', width: 20 },
        { header: 'Assigned to', width: 20 },
        { header: 'Reported', width: 18 },
        { header: 'Last activity', width: 18 },
        { header: 'Closed', width: 18 },
        { header: 'Times reopened', width: 15 },
        { header: 'Fixed in', width: 14 },
        { header: 'Fix link', width: 30 },
        { header: 'Steps', width: 60 },
        { header: 'Expected', width: 40 },
        { header: 'Actual', width: 40 },
        { header: 'Link', width: 40 },
      ],
      rows: data,
    },
  ]);
  return { bytes, filename: `hostelcare-bugs-${istDate(now)}.xlsx`, count: rows.length };
}

// ── The Monday summary ──────────────────────────────────────────────────────

const SEND_HOUR = 9;
const span = (hours: number | null) => (hours === null ? 'no data yet' : hours < 48 ? `${Math.round(hours)} h` : `${Math.round(hours / 24)} days`);
const listUrl = (filters: Record<string, string>) => `${publicWebUrl}/bugs#bugs?${new URLSearchParams(filters).toString()}`;

/**
 * Every Monday from 09:00 India time, each super admin gets last week's
 * numbers (unless they switched it off). Nothing is sent while the tracker has
 * no bugs. BugSummaryLog's unique key makes each go once.
 */
export async function runWeeklySummary(now = new Date()): Promise<number> {
  const shifted = new Date(now.getTime() + IST_MS);
  if (shifted.getUTCDay() !== 1 || shifted.getUTCHours() < SEND_HOUR) return 0;
  if ((await db.bug.count()) === 0) return 0;
  const admins = await db.user.findMany({ where: { role: Role.SUPER_ADMIN, deactivatedAt: null }, select: { id: true, name: true, email: true } });
  const off = new Set((await db.bugNotifyPrefs.findMany({ where: { userId: { in: admins.map((a) => a.id) }, emailOff: { has: 'WEEKLY' } }, select: { userId: true } })).map((p) => p.userId));
  const to = admins.filter((a) => !off.has(a.id) && !isPlaceholderEmail(a.email));
  if (!to.length) return 0;

  const thisWeek = weekStart(now);
  const lastWeek = new Date(thisWeek.getTime() - 7 * DAY);
  const [t, trend, w, oldest] = await Promise.all([
    tiles(now),
    weeks(now, 2),
    walk(lastWeek),
    db.bug.findMany({ where: { status: { in: NOT_CLOSED } }, orderBy: { createdAt: 'asc' }, take: 5, select: { number: true, title: true, severity: true, createdAt: true, module: { select: { name: true } } } }),
  ]);
  const devs = await developers(w);
  const tile = (key: string) => t.find((x) => x.key === key)!;
  const week = trend[0];
  const day = (d: Date) => new Date(d.getTime() + IST_MS).toLocaleDateString('en-IN', { day: 'numeric', month: 'short', timeZone: 'UTC' });
  const attention = ['unassigned', 'reopened', 'critical', 'older-30'].map(tile).filter((x) => x.count > 0);
  const date = istDate(now);

  let sent = 0;
  for (const a of to) {
    const key = `bug-weekly:${date}:${a.id}`;
    const claimed = await db.bugSummaryLog.createMany({ data: { key, toEmail: a.email }, skipDuplicates: true });
    if (claimed.count === 0) continue;
    const message = crmEmail({
      title: `Bug tracker: week of ${day(lastWeek)}`,
      intro: `Hi ${a.name}, last week ${week.opened} ${week.opened === 1 ? 'bug was' : 'bugs were'} reported and ${week.closed} closed. ${tile('open').count} ${tile('open').count === 1 ? 'is' : 'are'} open now.`,
      badge: 'Weekly summary',
      figures: [
        ['Open', String(tile('open').count)],
        ['Waiting for QA', String(tile('waiting-for-qa').count)],
        ['Reported', String(week.opened)],
        ['Closed', String(week.closed)],
      ],
      sections: [
        { heading: 'Needs attention', items: attention.map((x) => ({ text: `${x.label}: ${x.count}`, url: listUrl(x.filters), tone: 'warning' as const })), empty: 'Nothing unassigned, reopened, critical or older than 30 days.' },
        {
          heading: 'Oldest open bugs',
          items: oldest.map((b) => ({ text: `${bugKey(b.number)}  ${b.title}`, sub: `${words(b.severity)} · ${b.module.name}`, aside: `${Math.floor((now.getTime() - b.createdAt.getTime()) / DAY)} days`, url: bugUrl(b.number) })),
        },
        {
          heading: 'Developers',
          items: devs.map((d) => ({ text: d.name, sub: `${d.toFix + d.reopened} to fix (${d.reopened} reopened) · ${d.waitingForQa} waiting for QA`, aside: `${d.fixed} fixed${d.sentBack ? `, ${d.sentBack} sent back` : ''}` })),
        },
        {
          heading: 'Last week',
          items: [
            { text: 'Average time to fix', aside: span(average(w.fixHours)) },
            { text: 'Average time for QA to verify', aside: span(average(w.verifyHours)) },
            { text: 'Fixes QA sent back', aside: `${w.sentBack.size} of ${w.fixed.size}` },
          ],
        },
      ],
      cta: { label: 'Open the dashboard', url: `${publicWebUrl}/bugs#dashboard` },
      reason: `You get this every Monday as the super admin. To stop it, open Notifications in the bug tracker: ${publicWebUrl}/bugs#notifications`,
      signoff: '— HostelCare bug tracker',
    });
    const r = await mail.send(a.email, message.subject, message.text, message.html);
    const status = r.mode === 'log' ? 'DRY_RUN' : r.sent ? 'SENT' : 'FAILED';
    await db.bugSummaryLog.update({ where: { key }, data: { status } });
    if (status !== 'FAILED') sent++;
  }
  return sent;
}
