/**
 * The automated tests, as test cases for the bug tracker (docs/bug-tracker-plan.md).
 *
 *   npx tsx scripts/test-cases-export.ts [out.xlsx | out.json]
 *
 * Reads the checks the code runs on every release (the smoke test, the
 * permission audit, the bug tracker's and the blog's tests, and the hostel
 * isolation test) and writes them as checklists in the bug tracker's import
 * format: one row per item, Checklist / App / Description / Item / How to
 * test it / Module. Import the file under Bug tracker → Tests → Import.
 *
 * Each check becomes an item: its words are already plain English. A check
 * that only adds to the one before it ("and …") is folded into that item, and
 * an expected refusal ("(403)") becomes what the tester should see. The
 * permission audit's route-by-role matrix (thousands of generated rows) is not
 * a hand test and is left out; its named checks are in.
 *
 * Reads files only: no database, no network. Run it again as tests are added.
 */
import { readFileSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { writeXlsx, type Cell } from '../src/lib/xlsx';

const ROOT = join(__dirname, '..');
const out = process.argv[2] ?? join(ROOT, 'docs', 'test-cases', 'hostelcare-test-cases.xlsx');

interface Item {
  title: string;
  detail: string[];
}
interface List {
  name: string;
  app: string;
  description: string;
  module: string;
  items: Item[];
}

// ── Each smoke section: its checklist and module (the header's start → [checklist, module]) ──

const SMOKE: [string, string, string][] = [
  ['(start)', 'Sign-in and the basics', 'Sign-in and account'],
  ['Sprint 6: platform settings', 'Platform settings and own profile', 'Super admin and plans'],
  ['Sprint 6: tenant CRUD', 'Hostels: add, edit, suspend, remove', 'Super admin and plans'],
  ['Platform invoicing', 'Platform invoices and payments', 'Super admin and plans'],
  ['Sprint 2: rooms, beds', 'Rooms, beds, residents and occupancy', 'Properties and rooms'],
  ['Sprint 3: rent, payments', 'Rent, payments, expenses and the mess fee', 'Billing and payments'],
  ['Sprint 6: staff CRUD', 'Staff accounts', 'Staff and roles'],
  ['Sprint 4: notices', 'Notices and WhatsApp reminders', 'Notices and messages'],
  ['Sprint 5: multi-property', 'Several properties', 'Properties and rooms'],
  ['Sprint 5: ESSL', 'Biometric attendance (ESSL)', 'Attendance and leave'],
  ['Sprint 5: analytics', 'Analytics', 'Reports'],
  ['Pricing modes', 'Pricing by bed or by room', 'Billing and payments'],
  ['Plan limits', 'Plan limits: properties and beds', 'Super admin and plans'],
  ['Property setup details', 'Property setup details', 'Onboarding and setup'],
  ['Property detail + edit', 'Property details and editing', 'Properties and rooms'],
  ['Property floor plan', 'Property floor plan and room details', 'Properties and rooms'],
  ['Student CRUD', 'Residents: add, edit and details', 'Residents'],
  ['Mess calendar', 'Mess calendar and billing modes', 'Mess'],
  ['FIXED_MONTHLY', 'Mess calendar and billing modes', 'Mess'],
  ['PER_DAY', 'Mess calendar and billing modes', 'Mess'],
  ['ACTUAL_COST', 'Mess calendar and billing modes', 'Mess'],
  ['Leaving the mess', 'Mess calendar and billing modes', 'Mess'],
  ['Mess inventory', 'Mess inventory', 'Mess'],
  ['Mess complaints', 'Mess complaints', 'Mess'],
  ['Invoice hygiene', 'Invoices: overpayment, voiding, payment details', 'Billing and payments'],
  ['Billing identity', 'Billing details and automatic reminders', 'Billing and payments'],
  ['WhatsApp: what went out', 'WhatsApp: sent messages, receipts and replies', 'Notices and messages'],
  ['Relayed uploads', 'File uploads are checked first', 'Other'],
  ['Expense hygiene', 'Expenses: edit, delete and the stock guard', 'Expenses'],
  ['Custom expense categories', 'Custom expense categories', 'Expenses'],
  ['Inventory intelligence', 'Mess inventory: valuation, consumption, wastage', 'Mess'],
  ['A brand-new item', 'Mess inventory: valuation, consumption, wastage', 'Mess'],
  ['Deposit, KYC', 'Deposit, KYC and police verification', 'Residents'],
  ['Account: export', 'Account export and deletion request', 'Sign-in and account'],
  ['Student portal', 'Resident portal: requests, profile, documents', 'Residents'],
  ['Plan details', 'Plan details in Settings', 'Super admin and plans'],
  ['Two-step verification', 'Two-step sign-in by email code', 'Sign-in and account'],
  ['Invoice PDF', 'Invoice PDF', 'Billing and payments'],
  ['Fee cycles', 'Fee cycles, statuses and offline payments', 'Billing and payments'],
  ['Email notifications', 'Email notifications', 'Notices and messages'],
  ['Billing rules', 'Billing rules: pro-rata, late fee, charges, GST', 'Billing and payments'],
  ['Online collection', 'Online collection: Razorpay links and Route', 'Billing and payments'],
  ['Collection hardening', 'Collections: reconciliation, refunds, virtual accounts', 'Billing and payments'],
  ['Move-out and settlement', 'Move-out and settlement', 'Stays and bookings'],
  ['Movement and guardians', 'Passes, gate, late returns, visitors, guardians', 'Gate and visitors'],
  ['Mess and growth', 'Meal opt-out, SLAs, vendors, Tally, vacancy page, salary', 'Mess'],
  ['Sprint 0 (TEPL', 'Enterprise: modules and their switches', 'Enterprise'],
  ['Sprint 1 (TEPL)', 'Enterprise: employee records, leave policy, shift roster', 'Enterprise'],
  ['Sprint 2 (TEPL)', 'Enterprise: grievances, discipline, feedback, parcels, lost and found', 'Enterprise'],
  ['Sprint 3 (TEPL)', 'Enterprise: cleaning, room inventory, laundry, staff attendance, energy', 'Enterprise'],
  ['Sprint 4 (TEPL)', 'Enterprise: notices, broadcasts, outings, curfew, buses, visitors', 'Enterprise'],
  ['Sprint 5 (TEPL)', 'Enterprise: events, emergencies, canteen, asset tags', 'Enterprise'],
  ['Sprint 6 (TEPL)', 'Enterprise: medical, special needs, leadership view, HR feeds', 'Enterprise'],
  ['Employee hostels carry no money', 'Enterprise: no money shown, parent contact, move-out', 'Enterprise'],
  ['4 Nov 2026 (TEPL)', 'Enterprise: menu from a sheet, staff record, outings, reports', 'Enterprise'],
  ['Sprint 7 (TEPL)', 'Enterprise: statutory compliance, laundry feed, security', 'Enterprise'],
  ['Dormitory stays', 'Dormitory stays: bookings, check-in, check-out', 'Stays and bookings'],
  ['Editing and removing rooms', 'Editing and removing rooms', 'Properties and rooms'],
  ['CRM foundation', 'CRM: users, invites, two-step sign-in', 'CRM'],
  ['CRM contacts and lists', 'CRM: contacts and lists', 'CRM'],
  ['CRM deals', 'CRM: deals, pipeline and tasks', 'CRM'],
  ['CRM automation', 'CRM: alerts, reminders, summaries, dashboard', 'CRM'],
  ['CRM AI (C5)', 'CRM AI: guards, usage and the spend cap', 'CRM'],
  ['CRM AI (C6)', 'CRM AI: lead scores, focus, insights, campaigns', 'CRM'],
  ['CRM assistant', 'CRM assistant', 'CRM'],
  ['CRM contact validation', 'CRM: contact validation', 'CRM'],
  ['Lead core', 'Leads: website form, grading, owner', 'CRM'],
  ['Self-serve free trial', 'Self-serve free trial', 'Onboarding and setup'],
  ['Demo booking', 'Demo booking', 'CRM'],
  ['Lead sources', 'Leads: Meta, WhatsApp, call outcomes', 'CRM'],
  ['Pipeline and trial journey', 'Leads: pipeline and trial journey', 'CRM'],
  ['Opt-out, nurture', 'Leads: opt-out, nurture and the funnel', 'CRM'],
  ['WhatsApp from a CRM contact', 'CRM: WhatsApp on a contact’s timeline', 'CRM'],
  ['Follow-up dashboard', 'CRM: follow-up dashboard', 'CRM'],
  ['Authenticator app', 'Authenticator app sign-in', 'Sign-in and account'],
  ['Access windows', 'Trial and plan access, expiry reminders', 'Super admin and plans'],
];

const AUDIT: [string, string][] = [
  ['(start)', 'Permissions: platform team sign-in'],
  ['Website blog', 'Permissions: website blog'],
  ['Bug tracker', 'Permissions: bug tracker'],
  ['Cross-tenant isolation', 'Permissions: one hostel cannot reach another'],
  ['Custom roles', 'Permissions: custom roles'],
];

// ── Turning a check into an item ────────────────────────────────────────────

const EXPECTED: Record<string, string> = {
  '400': 'Expected: it is refused, with a message saying what is wrong.',
  '401': 'Expected: it is refused; the person has to sign in (again).',
  '403': 'Expected: it is refused; this person is not allowed to do it.',
  '404': 'Expected: it is refused as not found.',
  '409': 'Expected: it is refused because it clashes with something that exists.',
  '410': 'Expected: it is refused because it has expired or was used already.',
  '413': 'Expected: it is refused as too large.',
  '422': 'Expected: it is refused, with the reasons listed.',
  '429': 'Expected: too many tries; it asks to wait.',
  '503': 'Expected: it says the feature is not set up.',
};

/** A string literal's text: escapes undone, `${…}` shown as "…". */
const literal = (raw: string) =>
  raw
    .replace(/\$\{[^}]*\}/g, '…')
    .replace(/\\n/g, ' ')
    .replace(/\\(.)/g, '$1')
    .replace(/\s+/g, ' ')
    .trim();

/** The first argument of each check(…) or test(…) on a line. */
function names(line: string, fn: 'check' | 'test'): string[] {
  const re = new RegExp(`\\b${fn}\\(\\s*(['"\`])((?:\\\\.|(?!\\1).)*)\\1`, 'g');
  return [...line.matchAll(re)].map((m) => literal(m[2]));
}

function toItem(text: string): { title: string; detail: string[]; follows: boolean } {
  // "(201) and it gets a key": a success code in the middle says nothing to a tester.
  let t = text.replace(/\s*\((?:200|201|204)\)(?=\s|$)/g, '');
  const detail: string[] = [];
  const code = /\s*\((\d{3})(?:[^)]*)?\)\s*[.:]?$/.exec(t);
  if (code) {
    t = t.slice(0, code.index).trim();
    if (EXPECTED[code[1]]) detail.push(EXPECTED[code[1]]);
  }
  // "and …", "…and …", "but …": the check before it, taken further.
  const follows = /^(?:…|\.\.\.)?\s*(?:and|but|or|also|then|while)\b/i.test(t) || /^…/.test(t);
  t = t.replace(/^(?:…|\.\.\.)\s*/, '');
  t = t.charAt(0).toUpperCase() + t.slice(1);
  if (t.length > 200) {
    detail.unshift(t);
    t = `${t.slice(0, 196).trimEnd()}…`;
  }
  return { title: t, detail, follows };
}

function add(list: List, text: string) {
  if (!text || text.length < 2) return;
  const it = toItem(text);
  const prev = list.items.at(-1);
  if (it.follows && prev) {
    const more = it.title.replace(/^(?:and|but|or|also|then|while)\s+/i, '');
    prev.detail.push(`Also: ${more.charAt(0).toLowerCase()}${more.slice(1)}`, ...it.detail);
    return;
  }
  // A check run in a loop shows once.
  if (list.items.some((i) => i.title === it.title)) return;
  list.items.push({ title: it.title, detail: it.detail });
}

// ── The suites ──────────────────────────────────────────────────────────────

const lists = new Map<string, List>();
function list(name: string, module: string, app: string, description: string): List {
  let l = lists.get(name);
  if (!l) lists.set(name, (l = { name, app, description, module, items: [] }));
  return l;
}
const unknown: string[] = [];

function smoke() {
  const lines = readFileSync(join(ROOT, 'scripts', 'smoke.mjs'), 'utf8').split('\n');
  let header = '(start)';
  let started = false;
  for (const line of lines) {
    if (line.includes("console.log('▶ Booting")) started = true;
    if (!started) continue;
    const h = /^ {2}\/\/ ── (.*?)\s*─*\s*$/.exec(line);
    if (h) {
      // A header that wraps onto a second comment line ("and …") belongs to the one before.
      if (!/^and\b/.test(h[1])) header = h[1].replace(/\s*─+$/, '');
      continue;
    }
    for (const n of names(line, 'check')) {
      const hit = SMOKE.find(([start]) => header.startsWith(start));
      if (!hit && !unknown.includes(header)) unknown.push(header);
      const [, name, module] = hit ?? [header, header.replace(/\s*\([^)]*\)/g, '').slice(0, 80), 'Other'];
      add(list(name, module, '', `From the automated smoke test (scripts/smoke.mjs), section “${header === '(start)' ? 'start-up and sign-in' : header}”. The same checks run against the API on every release.`), n);
    }
  }
}

function audit() {
  const lines = readFileSync(join(ROOT, 'scripts', 'permission-audit.mjs'), 'utf8').split('\n');
  let header = '(start)';
  for (const line of lines) {
    const h = /^ {2}\/\/ ── (.*?)\s*─*\s*$/.exec(line);
    if (h) {
      header = h[1];
      continue;
    }
    // The route-by-role matrix is generated, not a hand test.
    if (/ALLOWED|DENIED/.test(line)) continue;
    for (const n of names(line, 'check')) {
      const hit = AUDIT.find(([start]) => header.startsWith(start)) ?? AUDIT[0];
      add(list(hit[1], 'Staff and roles', '', 'From the automated permission audit (scripts/permission-audit.mjs): who can and cannot do what. The same checks run on every release, with every role signed in.'), n);
    }
  }
}

function unitTests(file: string, name: string, module: string, app: string, about: string) {
  const lines = readFileSync(join(ROOT, 'src', 'tests', file), 'utf8').split('\n');
  for (const line of lines) {
    for (const n of names(line, 'test')) {
      // Setting up and clearing away test data is not something to test.
      if (/throwaway schema|clean slate|^seed |: set up /i.test(n)) continue;
      // "bugs workflow: who may do what" → "Workflow: who may do what"
      add(list(name, module, app, about), n.replace(/^(?:bugs?|blog)\s+([\w-]+):\s*/i, (_m, area: string) => `${area.charAt(0).toUpperCase()}${area.slice(1)}: `).replace(/^(?:bugs?|blog):\s*/i, ''));
    }
  }
}

smoke();
audit();
unitTests('bug-tracker.test.ts', 'Bug tracker', '', '', 'From the bug tracker’s automated tests (src/tests/bug-tracker.test.ts): accounts, reports, the fix-and-verify loop, notifications, releases, the board, test runs and GitHub.');
unitTests('blog-cms.test.ts', 'Website blog CMS', 'Website and blog', '', 'From the blog CMS’s automated tests (src/tests/blog-cms.test.ts): writing, checking, publishing and building posts.');
unitTests('isolation.test.ts', 'Data stays inside each hostel', 'Other', 'API', 'From the automated isolation test (src/tests/isolation.test.ts): one hostel’s data can never be read or changed by another. These run against the database, not by hand; listed so the team knows they exist.');

// ── The file ────────────────────────────────────────────────────────────────

const all = [...lists.values()].filter((l) => l.items.length);
for (const l of all) if (l.items.length > 200) throw new Error(`${l.name} has ${l.items.length} items; split it (a checklist holds at most 200).`);
const rows: Cell[][] = all.flatMap((l) => l.items.map((i, n) => [l.name, n === 0 ? l.app : '', n === 0 ? l.description : '', i.title, i.detail.join('\n\n').slice(0, 4000), l.module]));

// "….json" writes the same lists as JSON, to read them over before importing.
if (out.endsWith('.json')) writeFileSync(out, JSON.stringify(all, null, 2));
else writeFileSync(
  out,
  writeXlsx([
    {
      name: 'Test cases',
      columns: [
        { header: 'Checklist', width: 34 },
        { header: 'App', width: 13 },
        { header: 'Description', width: 40 },
        { header: 'Item', width: 60 },
        { header: 'How to test it', width: 60 },
        { header: 'Module', width: 24 },
      ],
      rows,
    },
  ]),
);
// eslint-disable-next-line no-console
console.log(`${all.length} checklists, ${rows.length} test cases → ${out}`);
if (unknown.length) console.warn(`Smoke sections with no name yet (filed under Other): ${unknown.join(' | ')}`);
