/**
 * audit-dev-frontend/audit.ts — Deterministic checkers for DEV-UI-001..012.
 *
 * Self-builds the project inventory from disk (replaces the system-prompt
 * skill's externally-injected inventory). Each rule = one async checker
 * fed { args, prdSlice, inventory } returning Finding[] (≥1 ok, or N err/warn).
 *
 * Heuristics are line-based and regex-based — NOT AST. The baseline scaffold
 * generators emit idiomatic code, so the heuristics work in practice. Edge
 * cases that don't match the templates fall through as ok (no false err).
 */
import path from 'node:path';
import { findFiles, readText, fileExists, readJson, directoryExists } from '../../../../lib/fs.js';
import type {
  AuditDevFrontendArgs,
  AuditReport,
  Finding,
  FrontendInventory,
  PageEntry,
  PrdRbacEntry,
  PrdSliceFrontend,
  RegistryEntry,
} from './types.js';

// ─── Page filename parsing ────────────────────────────────────────────────

const PAGE_FILENAME_RE = /^([A-Z]\w+?)(List|Detail|Form|Dashboard|Create|Edit|Home)Page\.tsx$/;

function parsePageFilename(file: string): Pick<PageEntry, 'entity' | 'kind'> {
  const base = path.basename(file);
  const m = PAGE_FILENAME_RE.exec(base);
  if (!m) return { entity: null, kind: 'other' };
  const kind = m[2].toLowerCase() as PageEntry['kind'];
  return { entity: m[1], kind };
}

// ─── Inventory builder ────────────────────────────────────────────────────

export async function buildInventory(projectPath: string): Promise<FrontendInventory> {
  const pages = await discoverPages(projectPath);
  const registries = await discoverRegistries(projectPath);
  const i18n = await discoverI18n(projectPath);
  return { pages, registries, i18n };
}

async function discoverPages(projectPath: string): Promise<PageEntry[]> {
  const patterns = ['src/pages/**/*.tsx', 'src/features/**/pages/**/*.tsx'];
  const found = new Set<string>();
  for (const pat of patterns) {
    for (const f of await findFiles(pat, { cwd: projectPath })) {
      const rel = path.relative(projectPath, f).replace(/\\/g, '/');
      if (rel.endsWith('.test.tsx') || rel.endsWith('.spec.tsx')) continue;
      found.add(rel);
    }
  }
  return [...found].map((file) => ({ file, ...parsePageFilename(file) }));
}

async function discoverRegistries(projectPath: string): Promise<RegistryEntry[]> {
  const candidates = await findFiles('src/extensions/**/*.ts', { cwd: projectPath });
  const out: RegistryEntry[] = [];
  for (const abs of candidates) {
    const rel = path.relative(projectPath, abs).replace(/\\/g, '/');
    const source = await readText(abs);
    if (!/PageRegistry\.register\s*\(/.test(source) && !/ComponentRegistry\.register\s*\(/.test(source)) {
      continue;
    }

    // Build a name → importPath map from `const X = lazy(() => import('@/...'))`
    // or `const X = lazyWithRetry(() => import('@/...'))` (two-step pattern
    // used by componentRegistry.generated.ts — the SDK-sanctioned wrapper
    // adds retry logic but is otherwise indistinguishable from React.lazy).
    const lazyConsts = new Map<string, string>();
    const lazyConstRe = /\bconst\s+(\w+)\s*=\s*(?:lazy|lazyWithRetry)\s*\(\s*\(\s*\)\s*=>\s*import\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g;
    let mc: RegExpExecArray | null;
    while ((mc = lazyConstRe.exec(source)) !== null) {
      lazyConsts.set(mc[1], mc[2]);
    }

    const keys: string[] = [];
    const imports: RegistryEntry['imports'] = [];

    // Pattern A — inline lazy/lazyWithRetry: `register('key', lazy(() => import('@/...')))`
    // Restrict the gap between key and the wrapper call to whitespace only —
    // otherwise the non-greedy match jumps across several register() calls to a
    // later wrapper invocation.
    const inlineRe = /(?:Page|Component)Registry\.register\s*\(\s*['"`]([^'"`]+)['"`]\s*,\s*(?:lazy|lazyWithRetry)\s*\(\s*\(\s*\)\s*=>\s*import\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g;
    let m: RegExpExecArray | null;
    while ((m = inlineRe.exec(source)) !== null) {
      const key = m[1];
      const importPath = m[2];
      keys.push(key);
      imports.push({ key, importPath, resolvedAbsPath: await resolveImport(abs, importPath, projectPath) });
    }

    // Pattern B — const reference: `register('key', SomeConst)`
    const refRe = /(?:Page|Component)Registry\.register\s*\(\s*['"`]([^'"`]+)['"`]\s*,\s*(\w+)\s*\)/g;
    while ((m = refRe.exec(source)) !== null) {
      const key = m[1];
      const constName = m[2];
      const importPath = lazyConsts.get(constName);
      if (!importPath) continue; // not a lazy const we tracked
      // Skip if already added by inline pattern (rare, but possible if both used in the same file)
      if (keys.includes(key)) continue;
      keys.push(key);
      imports.push({ key, importPath, resolvedAbsPath: await resolveImport(abs, importPath, projectPath) });
    }

    out.push({ file: rel, keys, imports });
  }
  return out;
}

async function resolveImport(
  registryAbsPath: string,
  importPath: string,
  projectPath: string,
): Promise<string | null> {
  // Resolve `@/` alias against `<projectPath>/src/`.
  let target: string;
  if (importPath.startsWith('@/')) {
    target = path.resolve(projectPath, 'src', importPath.slice(2));
  } else if (importPath.startsWith('.')) {
    target = path.resolve(path.dirname(registryAbsPath), importPath);
  } else {
    // External package — assume valid (we don't try to resolve node_modules).
    return null;
  }
  // Try with .tsx, .ts, /index.tsx, /index.ts extensions.
  const candidates = [
    target,
    `${target}.tsx`,
    `${target}.ts`,
    path.join(target, 'index.tsx'),
    path.join(target, 'index.ts'),
  ];
  for (const c of candidates) {
    if (await fileExists(c)) return c;
  }
  return null;
}

async function discoverI18n(projectPath: string): Promise<{ locales: string[]; namespaces: string[] }> {
  const localesDir = path.join(projectPath, 'src', 'locales');
  if (!(await directoryExists(localesDir))) {
    // Try src/i18n/locales as fallback
    const alt = path.join(projectPath, 'src', 'i18n', 'locales');
    if (!(await directoryExists(alt))) return { locales: [], namespaces: [] };
    return discoverI18nFrom(alt);
  }
  return discoverI18nFrom(localesDir);
}

async function discoverI18nFrom(dir: string): Promise<{ locales: string[]; namespaces: string[] }> {
  const files = await findFiles('*/*.json', { cwd: dir });
  const locales = new Set<string>();
  const namespaces = new Set<string>();
  for (const abs of files) {
    const rel = path.relative(dir, abs).replace(/\\/g, '/');
    const [loc, fname] = rel.split('/');
    if (loc && fname && fname.endsWith('.json')) {
      locales.add(loc);
      namespaces.add(fname.slice(0, -'.json'.length));
    }
  }
  return { locales: [...locales].sort(), namespaces: [...namespaces].sort() };
}

// ─── PRD slice loader ─────────────────────────────────────────────────────

export async function loadPrdSlice(prdSlicePath: string | undefined): Promise<PrdSliceFrontend> {
  if (!prdSlicePath) return {};
  return readJson<PrdSliceFrontend>(path.resolve(prdSlicePath));
}

// ─── Helpers ──────────────────────────────────────────────────────────────

function makeOk(code: string, params: Record<string, unknown> = {}): Finding {
  return {
    dimension: 'devFrontend',
    code,
    severity: 'ok',
    label: `${code.replace(/-/g, '_')}_ok`,
    params,
    solution: '',
    autoFixable: false,
  };
}

function makeErr(
  code: string,
  params: Record<string, unknown>,
  solution: string,
  extra: Partial<Finding> = {},
): Finding {
  return {
    dimension: 'devFrontend',
    code,
    severity: 'err',
    label: `${code.replace(/-/g, '_')}_err`,
    params,
    solution,
    autoFixable: extra.autoFixable ?? false,
    ...extra,
  };
}

function makeWarn(
  code: string,
  params: Record<string, unknown>,
  solution: string,
  extra: Partial<Finding> = {},
): Finding {
  return {
    dimension: 'devFrontend',
    code,
    severity: 'warn',
    label: `${code.replace(/-/g, '_')}_warn`,
    params,
    solution,
    autoFixable: extra.autoFixable ?? false,
    ...extra,
  };
}

// Normalise PRD entity/kind for matching against page inventory.
function screenKey(entity: string | null | undefined, kind: string | null | undefined): string {
  return `${(entity ?? '').toLowerCase()}|${(kind ?? '').toLowerCase()}`;
}

// ─── Rule checkers ────────────────────────────────────────────────────────

interface CheckerInput {
  args: AuditDevFrontendArgs;
  prdSlice: PrdSliceFrontend;
  inventory: FrontendInventory;
  projectPath: string;
}

async function checkDevUi001(input: CheckerInput): Promise<Finding[]> {
  const { prdSlice, inventory } = input;
  const screens = prdSlice.screens ?? [];
  if (screens.length === 0) return [makeOk('DEV-UI-001', { count: 0, note: 'no screens in PRD slice' })];

  const inventoryKeys = new Set(
    inventory.pages
      .filter((p) => p.entity)
      .map((p) => screenKey(p.entity, p.kind)),
  );

  const missing: string[] = [];
  for (const s of screens) {
    if (!s.entity || !s.kind) continue;
    if (!inventoryKeys.has(screenKey(s.entity, s.kind))) {
      missing.push(`${s.entity}/${s.kind}`);
    }
  }
  if (missing.length === 0) return [makeOk('DEV-UI-001', { count: screens.length })];
  return [makeErr(
    'DEV-UI-001',
    { missing: missing.join(',') },
    'Re-run the Frontend phase. The subagent must call scaffold-component for each missing page, using the matching SmartComponent pattern from the PRD slice.',
    { fixSkill: 'frontend-component', fixPhaseKey: 'frontend', autoFixable: true },
  )];
}

async function checkDevUi002(input: CheckerInput): Promise<Finding[]> {
  const { inventory } = input;
  if (inventory.pages.length === 0) return [makeOk('DEV-UI-002', { note: 'no pages on disk' })];

  // Build a set of resolved import target abs paths from all registries.
  const registeredAbs = new Set<string>();
  for (const reg of inventory.registries) {
    for (const imp of reg.imports) {
      if (imp.resolvedAbsPath) registeredAbs.add(imp.resolvedAbsPath);
    }
  }

  const orphanFindings: Finding[] = [];
  for (const page of inventory.pages) {
    const abs = path.resolve(input.projectPath, page.file);
    if (registeredAbs.has(abs)) continue;
    orphanFindings.push(makeErr(
      'DEV-UI-002',
      { pages: page.file },
      'Either re-run the routes scaffolder to regenerate the registry, or add a manual lazy-import entry. The DB-driven router fails to resolve unregistered pages.',
      { file: page.file, autoFixable: true, fixSkill: 'frontend-routes', fixPhaseKey: 'frontend' },
    ));
  }
  if (orphanFindings.length === 0) return [makeOk('DEV-UI-002')];
  return orphanFindings;
}

async function checkDevUi003(input: CheckerInput): Promise<Finding[]> {
  const { inventory } = input;
  const broken: Finding[] = [];
  for (const reg of inventory.registries) {
    for (const imp of reg.imports) {
      if (imp.resolvedAbsPath === null && !imp.importPath.includes('node_modules')) {
        // External import returns null too; only flag those that look like local @/ or relative paths.
        if (imp.importPath.startsWith('@/') || imp.importPath.startsWith('.')) {
          broken.push(makeErr(
            'DEV-UI-003',
            { broken: `${reg.file}→${imp.importPath}` },
            'Either restore the missing files or remove the orphan import entries from the registry. Lazy-imports that resolve to non-existent paths produce a runtime error on first navigation, not at build time.',
            { file: reg.file, autoFixable: false },
          ));
        }
      }
    }
  }
  if (broken.length === 0) return [makeOk('DEV-UI-003')];
  return broken;
}

async function checkDevUi004(input: CheckerInput): Promise<Finding[]> {
  const { inventory, args } = input;
  if (inventory.i18n.locales.length === 0) {
    return [makeOk('DEV-UI-004', { note: 'no i18n locales — skipping' })];
  }
  const expectedNs = `${args.appCode}.${args.moduleCode}`;
  const altNs = args.moduleCode;
  const missing: string[] = [];
  for (const loc of inventory.i18n.locales) {
    // The namespace must exist somewhere in the locale's file set.
    const has = inventory.i18n.namespaces.includes(expectedNs) || inventory.i18n.namespaces.includes(altNs);
    if (!has) missing.push(`${loc}.${expectedNs}`);
  }
  if (missing.length === 0) return [makeOk('DEV-UI-004', { namespace: expectedNs })];
  return [makeWarn(
    'DEV-UI-004',
    { missing: missing.join(','), expectedNamespace: expectedNs },
    `Add the missing namespace JSON files for each locale (typically src/locales/<locale>/${expectedNs}.json). Even an empty {} is preferable — i18next logs a warning but does not crash.`,
    { autoFixable: true },
  )];
}

async function checkDevUi005(input: CheckerInput): Promise<Finding[]> {
  const { inventory, projectPath } = input;
  const violators: Finding[] = [];
  for (const page of inventory.pages) {
    if (!page.entity) continue;
    if (page.kind === 'dashboard' || page.kind === 'home') continue;
    const abs = path.resolve(projectPath, page.file);
    const source = await readText(abs);
    if (/<PageTemplate[\s>]/.test(source)) continue;
    violators.push(makeWarn(
      'DEV-UI-005',
      { pages: page.file },
      'Wrap each listed page with <PageTemplate title="...">{...}</PageTemplate>. The template is the single source of truth for layout (header / sidebar / breadcrumbs).',
      { file: page.file, autoFixable: true },
    ));
  }
  if (violators.length === 0) return [makeOk('DEV-UI-005')];
  return violators;
}

async function checkDevUi006(input: CheckerInput): Promise<Finding[]> {
  const { inventory, projectPath } = input;
  const violators: Finding[] = [];
  const writeKeywords = /\b(?:Create|Edit|Delete|Update|New|Add|Remove)\b/;
  for (const page of inventory.pages) {
    if (page.kind === 'dashboard' || page.kind === 'home') continue;
    const abs = path.resolve(projectPath, page.file);
    const source = await readText(abs);
    if (!writeKeywords.test(source)) continue;
    if (/PermissionGuard\b|useHasPermission\b/.test(source)) continue;
    violators.push(makeWarn(
      'DEV-UI-006',
      { pages: page.file },
      'Wrap each write button with <PermissionGuard permission="<key>">...</PermissionGuard> or short-circuit the handler with useHasPermission. Without the gate, unauthorized users see a button that throws on click instead of being hidden.',
      { file: page.file, autoFixable: false },
    ));
  }
  if (violators.length === 0) return [makeOk('DEV-UI-006')];
  return violators;
}

async function checkDevUi007(input: CheckerInput): Promise<Finding[]> {
  const { inventory, projectPath } = input;
  const violators: Finding[] = [];
  for (const page of inventory.pages) {
    const abs = path.resolve(projectPath, page.file);
    const dir = path.dirname(abs);
    const base = path.basename(abs, '.tsx');
    const sibling = path.join(dir, `${base}.test.tsx`);
    const sibling2 = path.join(dir, '__tests__', `${base}.test.tsx`);
    if ((await fileExists(sibling)) || (await fileExists(sibling2))) continue;
    violators.push(makeWarn(
      'DEV-UI-007',
      { pages: page.file },
      'Re-run scaffold-tests --layer frontend for each listed page, or add a minimal smoke test that mounts the page with a Test wrapper providing QueryClient + i18n.',
      { file: page.file, autoFixable: true, fixSkill: 'testing', fixPhaseKey: 'frontend' },
    ));
  }
  if (violators.length === 0) return [makeOk('DEV-UI-007')];
  return violators;
}

async function checkDevUi008(input: CheckerInput): Promise<Finding[]> {
  const { prdSlice, inventory } = input;
  const screens = prdSlice.screens ?? [];
  // No PRD screens to compare against → can't detect ghosts → ok.
  if (screens.length === 0) return [makeOk('DEV-UI-008', { note: 'no PRD screens to compare' })];

  const prdKeys = new Set(screens.filter((s) => s.entity && s.kind).map((s) => screenKey(s.entity, s.kind)));
  const ghosts: string[] = [];
  for (const page of inventory.pages) {
    if (!page.entity) continue;
    if (!prdKeys.has(screenKey(page.entity, page.kind))) {
      ghosts.push(page.file);
    }
  }
  if (ghosts.length === 0) return [makeOk('DEV-UI-008')];
  return [makeWarn(
    'DEV-UI-008',
    { pages: ghosts.join(',') },
    'Either re-add the corresponding screen to the PRD slice if it was removed by mistake, or delete the page file AND remove its registry entry. Leaving ghost pages in the registry leaves dead routes in the Studio menu.',
    { autoFixable: false },
  )];
}

// ─── DEV-UI-009..012 (Track D) ────────────────────────────────────────────

async function checkDevUi009(input: CheckerInput): Promise<Finding[]> {
  const { prdSlice, inventory } = input;
  const useCases = prdSlice.useCases ?? [];
  if (useCases.length === 0) return [makeOk('DEV-UI-009', { note: 'no use cases in PRD' })];

  const inventoryEntities = new Set(inventory.pages.filter((p) => p.entity).map((p) => p.entity!.toLowerCase()));
  const uncovered: string[] = [];
  for (const uc of useCases) {
    if (!uc.entity) continue;
    if (!inventoryEntities.has(uc.entity.toLowerCase())) {
      uncovered.push(`${uc.code}(${uc.entity})`);
    }
  }
  if (uncovered.length === 0) return [makeOk('DEV-UI-009', { count: useCases.length })];
  return [makeErr(
    'DEV-UI-009',
    { useCases: uncovered.join(',') },
    'Each PRD use case must have at least one page targeting its primary entity. Re-run scaffold-component to generate the missing pages.',
    { fixSkill: 'frontend-component', fixPhaseKey: 'frontend', autoFixable: true },
  )];
}

async function checkDevUi010(input: CheckerInput): Promise<Finding[]> {
  const { prdSlice, inventory, projectPath } = input;
  const rules = prdSlice.businessRules ?? [];
  const uiRules = rules.filter((r) => r.enforcedAt === 'ui' || r.enforcedAt === 'both');
  if (uiRules.length === 0) return [makeOk('DEV-UI-010', { note: 'no UI-enforced business rules' })];

  // For each UI rule, find the form/edit page for its entity and check the source mentions
  // the rule code or has a Zod schema with refinements.
  const violators: Finding[] = [];
  for (const rule of uiRules) {
    if (!rule.entity) continue;
    const formPages = inventory.pages.filter((p) =>
      p.entity?.toLowerCase() === rule.entity!.toLowerCase()
      && (p.kind === 'form' || p.kind === 'create' || p.kind === 'edit'),
    );
    if (formPages.length === 0) {
      violators.push(makeWarn(
        'DEV-UI-010',
        { rule: rule.code, entity: rule.entity, missingPage: true },
        `No form/create/edit page found for entity ${rule.entity} — cannot enforce business rule ${rule.code} in UI.`,
        { autoFixable: false },
      ));
      continue;
    }
    for (const fp of formPages) {
      const abs = path.resolve(projectPath, fp.file);
      const source = await readText(abs);
      const mentionsRule = source.includes(rule.code);
      const hasZodRefine = /z\.object\([\s\S]*?\)\.refine\(/.test(source) || /\.refine\(/.test(source);
      if (!mentionsRule && !hasZodRefine) {
        violators.push(makeWarn(
          'DEV-UI-010',
          { rule: rule.code, entity: rule.entity, page: fp.file },
          `Form page ${fp.file} should enforce business rule ${rule.code} via Zod schema refine() or conditional render. Inject a refine using the rule's validExamples/invalidExamples.`,
          { file: fp.file, autoFixable: false },
        ));
      }
    }
  }
  if (violators.length === 0) return [makeOk('DEV-UI-010', { count: uiRules.length })];
  return violators;
}

async function checkDevUi011(input: CheckerInput): Promise<Finding[]> {
  const { prdSlice, inventory, projectPath, args } = input;
  const permissions = prdSlice.permissions ?? [];
  if (permissions.length === 0) return [makeOk('DEV-UI-011', { note: 'no PRD permissions to map' })];

  // Try to read controller [RequirePermission(...)] from backend if backendPath provided.
  let controllerPermissions: string[] = [];
  if (args.backendPath) {
    controllerPermissions = await scanControllerPermissions(args.backendPath);
  }

  // Map each permission → expected page (by entity match).
  const violators: Finding[] = [];
  const permsToCheck = controllerPermissions.length > 0
    ? Array.from(new Set([...controllerPermissions, ...permissions.map((p) => p.code)]))
    : permissions.map((p) => p.code);

  for (const permCode of permsToCheck) {
    // Find the matching PrdPermission entry (or derive entity from the perm key).
    const prdPerm = permissions.find((p) => p.code === permCode);
    const entity = prdPerm?.entity ?? deriveEntityFromPermissionKey(permCode);
    if (!entity) continue;
    const targetPages = inventory.pages.filter((p) => p.entity?.toLowerCase() === entity.toLowerCase());
    if (targetPages.length === 0) continue;
    for (const tp of targetPages) {
      const abs = path.resolve(projectPath, tp.file);
      const source = await readText(abs);
      const wrapped = new RegExp(`PermissionGuard[^>]*permission=\\{?["'\`]${permCode.replace(/\./g, '\\.')}["'\`]`).test(source);
      if (wrapped) continue;
      violators.push(makeErr(
        'DEV-UI-011',
        { page: tp.file, permission: permCode, entity },
        `Page ${tp.file} must wrap its body in <PermissionGuard permission="${permCode}">…</PermissionGuard>. The backend [RequirePermission] returns 403 silently to the user — the frontend guard hides the route entirely.`,
        { file: tp.file, autoFixable: true, fixSkill: 'audit-dev-frontend', fixPhaseKey: 'frontend' },
      ));
    }
  }
  if (violators.length === 0) return [makeOk('DEV-UI-011')];
  return violators;
}

function deriveEntityFromPermissionKey(key: string): string | null {
  // Convention: {module}.{section}.{action} → entity ≈ section (e.g. crm.contacts.read → contacts).
  const parts = key.split('.');
  if (parts.length >= 3) return parts[parts.length - 2];
  if (parts.length === 2) return parts[0];
  return null;
}

async function scanControllerPermissions(backendPath: string): Promise<string[]> {
  const controllers = await findFiles('**/*Controller.cs', { cwd: backendPath });
  const perms = new Set<string>();
  for (const abs of controllers) {
    const source = await readText(abs);
    const re = /\[RequirePermission\s*\(\s*["]([^"]+)["]/g;
    let m: RegExpExecArray | null;
    while ((m = re.exec(source)) !== null) {
      perms.add(m[1]);
    }
  }
  return [...perms].sort();
}

async function checkDevUi012(input: CheckerInput): Promise<Finding[]> {
  const { prdSlice, args } = input;
  const rbac: PrdRbacEntry[] = prdSlice.rbac ?? [];
  if (rbac.length === 0) return [makeOk('DEV-UI-012', { note: 'no PRD RBAC entries' })];
  if (!args.coreNavigationSeedPath) {
    return [makeOk('DEV-UI-012', { note: 'coreNavigationSeedPath not provided — skipping' })];
  }

  let source: string;
  try {
    source = await readText(path.resolve(args.coreNavigationSeedPath));
  } catch {
    return [makeWarn(
      'DEV-UI-012',
      { path: args.coreNavigationSeedPath, error: 'unreadable' },
      'Could not read CoreNavigationSeedDataProvider.cs to verify RBAC menu coverage.',
      { autoFixable: false },
    )];
  }

  // For each PRD RBAC entry granting nav-related permissions, the seed file should declare the nav with requiredPermissions.
  const violators: Finding[] = [];
  for (const entry of rbac) {
    for (const perm of entry.grants) {
      if (!source.includes(`"${perm}"`)) {
        violators.push(makeWarn(
          'DEV-UI-012',
          { actor: entry.actor, permission: perm, file: args.coreNavigationSeedPath },
          `Navigation seed does not reference permission "${perm}" granted to actor "${entry.actor}". Re-run scaffold-core-seed after updating the BA RBAC tables to include this permission in the navigation entry's requiredPermissions.`,
          { autoFixable: false, fixSkill: 'backend-core-seed', fixPhaseKey: 'core' },
        ));
        break; // one per actor is enough
      }
    }
  }
  if (violators.length === 0) return [makeOk('DEV-UI-012')];
  return violators;
}

// ─── DEV-UI-013 — hardcoded navigate() URL vs routes-helper ───────────────

async function checkDevUi013(input: CheckerInput): Promise<Finding[]> {
  const { inventory, projectPath } = input;
  const offenders: Array<{ file: string; url: string }> = [];
  for (const page of inventory.pages) {
    const abs = path.resolve(projectPath, page.file);
    const source = await readText(abs);
    if (!source) continue;
    // Match navigate('/...') or navigate("/...") or navigate(`/...`) — absolute literal.
    const re = /navigate\s*\(\s*(['"`])(\/[^'"`]+)\1\s*\)/g;
    let m: RegExpExecArray | null;
    while ((m = re.exec(source)) !== null) {
      offenders.push({ file: page.file, url: m[2] });
    }
  }
  if (offenders.length === 0) return [makeOk('DEV-UI-013')];
  return offenders.map((o) =>
    makeErr(
      'DEV-UI-013',
      { file: o.file, url: o.url },
      "Replace the hardcoded URL with a call to the per-module routes helper " +
        "(`import { routes } from '@/extensions/<module>Routes'`; then `navigate(routes.<section>.create())` etc.). " +
        "URL paths and DynamicRouter componentKeys must share a single source of truth — hardcoded literals drift the moment a route gets renamed.",
      { file: o.file, fixSkill: 'frontend-component', fixPhaseKey: 'frontend', autoFixable: true },
    ),
  );
}

// ─── DEV-UI-014 — stub helpers in list pages (return 0 / '' / null) ───────

async function checkDevUi014(input: CheckerInput): Promise<Finding[]> {
  const { inventory, projectPath } = input;
  const offenders: Array<{ file: string; helper: string }> = [];
  // Match named arrow/function helpers whose body returns a literal stub:
  //   const consumptionFor = (b) => 0
  //   function priceFor(item) { return ''; }
  //   const xFor = (b: Foo) => null
  // Restrict to List pages (the bug pattern that produced empty KPIs).
  const helperRe =
    /(?:const|let)\s+(\w+For)\s*=\s*\([^)]*\)\s*(?::\s*[^=]+)?=>\s*\(?\s*(0|''|""|null|false)\s*\)?\s*[,;]|function\s+(\w+For)\s*\([^)]*\)\s*(?::\s*[^=]+)?\{\s*(?:[^{}]{0,80}?)return\s+(0|''|""|null|false)\s*;\s*\}/g;
  for (const page of inventory.pages) {
    if (page.kind !== 'list') continue;
    const abs = path.resolve(projectPath, page.file);
    const source = await readText(abs);
    if (!source) continue;
    let m: RegExpExecArray | null;
    while ((m = helperRe.exec(source)) !== null) {
      offenders.push({ file: page.file, helper: m[1] ?? m[3] ?? '<anonymous>' });
    }
  }
  if (offenders.length === 0) return [makeOk('DEV-UI-014')];
  return offenders.map((o) =>
    makeErr(
      'DEV-UI-014',
      { file: o.file, helper: o.helper },
      `List page emits a stub helper (\`${o.helper}\`) returning a literal — typical "give-up fallback" when the DTO doesn't expose a needed field. Don't paper over the gap : either (a) declare the missing field as a computed attribute with a \`formula\` in the BA data model so scaffold-business projects it via LINQ, or (b) extend the list DTO to include the value computed by the backend service. Audit DM-016 enforces the first path at the BA level.`,
      { file: o.file, fixSkill: 'frontend-api-client', fixPhaseKey: 'data', autoFixable: false },
    ),
  );
}

// ─── DEV-UI-015 — api-client services match controller routes ────────────

interface ControllerEndpoint {
  /** Lower-cased verb: 'get' / 'post' / 'put' / 'delete' / 'patch'. */
  verb: string;
  /** Full route pattern, e.g. 'api/budgets/dashboard/consolidated'. Lower-cased, no leading slash, no `:id` token (replaced by `{id}`). */
  fullPath: string;
  /** Whether the action method declares a `[FromBody]` parameter (or non-decorated reference type for POST/PUT/PATCH). */
  hasBody: boolean;
  /** Source file (relative to backendPath). */
  file: string;
}

interface ServiceCall {
  verb: string;
  /** URL literal as written in the TS source, lower-cased, no leading `/api/` (axios baseURL prepends it). */
  url: string;
  /** Whether the axios call passes a body argument. */
  hasBody: boolean;
  file: string;
}

const C_HTTP_VERBS = ['Get', 'Post', 'Put', 'Delete', 'Patch'];

async function loadControllerEndpoints(backendPath: string): Promise<ControllerEndpoint[]> {
  const endpoints: ControllerEndpoint[] = [];
  const files = await findFiles('**/*Controller.cs', { cwd: backendPath });
  for (const abs of files) {
    const source = await readText(abs);
    if (!source) continue;
    const rel = path.relative(backendPath, abs).replace(/\\/g, '/');
    // Class-level [Route("...")] (above `public class XxxController`).
    const classRouteMatch = /\[Route\(\s*['"]([^'"]+)['"]\s*\)\][\s\S]{0,400}?public\s+(?:abstract\s+|sealed\s+)?class\s+\w+Controller\b/.exec(source);
    const baseRoute = classRouteMatch ? classRouteMatch[1].trim() : '';
    // Method-level [HttpVerb("route")] capturing the optional inline route + the method signature on the next line.
    const methodRe = new RegExp(
      `\\[Http(${C_HTTP_VERBS.join('|')})(?:\\(\\s*['"]([^'"]*)['"]\\s*\\))?\\s*\\][^\\n]*\\n[\\s\\S]{0,400}?public[^\\(]+\\(([^\\)]*)\\)`,
      'g',
    );
    let m: RegExpExecArray | null;
    while ((m = methodRe.exec(source)) !== null) {
      const verb = m[1].toLowerCase();
      const inlineRoute = (m[2] ?? '').trim();
      const params = m[3] ?? '';
      const merged = mergeRoutes(baseRoute, inlineRoute);
      const fullPath = normaliseRoute(merged);
      const hasBody = /\[FromBody\]/.test(params) || (verb !== 'get' && /\b(?:Dto|Command|Request|Model)\b\s+\w+/.test(params));
      endpoints.push({ verb, fullPath, hasBody, file: rel });
    }
  }
  return endpoints;
}

function mergeRoutes(base: string, inline: string): string {
  const b = base.replace(/^\/+|\/+$/g, '');
  const i = inline.replace(/^\/+|\/+$/g, '');
  if (!b && !i) return '';
  if (!i) return b;
  if (!b) return i;
  return `${b}/${i}`;
}

function normaliseRoute(route: string): string {
  return route
    .toLowerCase()
    // [controller] token expanded by ASP.NET → can't resolve here; replace with a placeholder that won't match a real path.
    .replace(/\[controller\]/g, '__controller__')
    // {id:guid} → {id}
    .replace(/\{(\w+)(?::[^}]+)?\}/g, '{$1}')
    .replace(/^\/+|\/+$/g, '');
}

async function loadServiceCalls(projectPath: string): Promise<ServiceCall[]> {
  const calls: ServiceCall[] = [];
  const patterns = ['src/features/**/services/*Service.ts', 'src/services/**/*.ts'];
  const found = new Set<string>();
  for (const pat of patterns) {
    for (const f of await findFiles(pat, { cwd: projectPath })) {
      found.add(path.relative(projectPath, f).replace(/\\/g, '/'));
    }
  }
  for (const rel of found) {
    const abs = path.join(projectPath, rel);
    const source = await readText(abs);
    if (!source) continue;
    // axios-style: apiClient.get('/path', ...) / apiClient.post('/path', body, ...) etc.
    const callRe = /\b(?:apiClient|axios|client|http)\s*\.\s*(get|post|put|delete|patch)\s*<[^>]*>?\s*\(\s*(['"`])([^'"`]+)\2\s*(,\s*([^,)]+))?/g;
    let m: RegExpExecArray | null;
    while ((m = callRe.exec(source)) !== null) {
      const verb = m[1].toLowerCase();
      const rawUrl = m[3];
      const secondArg = (m[5] ?? '').trim();
      // Heuristic for body argument : POST/PUT/PATCH with a non-empty second
      // arg that isn't an axios config object (`{ params: ... }` etc.).
      const hasBody =
        verb !== 'get' && verb !== 'delete' &&
        secondArg.length > 0 &&
        !secondArg.startsWith('{ params') &&
        !/^\{\s*params\s*:/.test(secondArg);
      const url = normaliseTsUrl(rawUrl);
      calls.push({ verb, url, hasBody, file: rel });
    }
  }
  return calls;
}

function normaliseTsUrl(url: string): string {
  // Convert template-literal `${id}` to `{id}` so it matches the controller `{id}` token.
  return url
    .toLowerCase()
    .replace(/\$\{[^}]+\}/g, '{id}')
    .replace(/^\/+|\/+$/g, '')
    // axios baseURL is /api — strip it so the comparison is against the route's
    // application-relative form (controllers list `api/...` in [Route]).
    .replace(/^api\//, '');
}

async function checkDevUi015(input: CheckerInput): Promise<Finding[]> {
  const { args, projectPath } = input;
  if (!args.backendPath) {
    return [makeOk('DEV-UI-015', { note: 'skipping — --backend-path not supplied' })];
  }
  const backendAbs = path.resolve(args.backendPath);
  const endpoints = await loadControllerEndpoints(backendAbs);
  if (endpoints.length === 0) {
    return [makeOk('DEV-UI-015', { note: 'no controllers found at backendPath' })];
  }
  const calls = await loadServiceCalls(projectPath);
  if (calls.length === 0) {
    return [makeOk('DEV-UI-015', { note: 'no axios services found' })];
  }

  // Endpoints normalised: strip `api/` prefix to align with TS calls (`apiClient` baseURL is `/api`).
  const endpointKeys = new Map<string, ControllerEndpoint>();
  for (const ep of endpoints) {
    const stripped = ep.fullPath.replace(/^api\//, '');
    endpointKeys.set(`${ep.verb} ${stripped}`, ep);
  }

  const mismatches: Array<{ call: ServiceCall; reason: string }> = [];
  for (const call of calls) {
    const key = `${call.verb} ${call.url}`;
    const ep = endpointKeys.get(key);
    if (!ep) {
      // Try fuzzy: same URL but different verb (typical "GET vs POST" mismatch).
      const candidates = Array.from(endpointKeys.values()).filter((e) => e.fullPath.replace(/^api\//, '') === call.url);
      if (candidates.length > 0) {
        mismatches.push({
          call,
          reason: `wrong HTTP verb — service uses '${call.verb.toUpperCase()}' but controller exposes '${candidates[0].verb.toUpperCase()}'`,
        });
      } else {
        mismatches.push({
          call,
          reason: `no controller route matches '${call.verb.toUpperCase()} /${call.url}' — typo or missing endpoint`,
        });
      }
      continue;
    }
    if (call.hasBody !== ep.hasBody) {
      mismatches.push({
        call,
        reason: ep.hasBody
          ? `controller expects a body ([FromBody]) but service does not send one`
          : `service sends a body but controller has no [FromBody] / mutation parameter`,
      });
    }
  }

  if (mismatches.length === 0) {
    return [makeOk('DEV-UI-015', { count: calls.length })];
  }
  return mismatches.map((mm) =>
    makeErr(
      'DEV-UI-015',
      { file: mm.call.file, verb: mm.call.verb.toUpperCase(), url: `/${mm.call.url}`, reason: mm.reason },
      `API client / controller drift: ${mm.reason}. Re-run scaffold-api-client with the corrected spec, or fix the controller route attribute. Mismatches at this layer surface as runtime 400/404 errors with no console diagnostic — exactly the dashboard-empty-cards pattern.`,
      { file: mm.call.file, fixSkill: 'frontend-api-client', fixPhaseKey: 'api', autoFixable: false },
    ),
  );
}

// ─── DEV-UI-016 — list pages must use <DataTable> from customisation-ui ───

async function checkDevUi016(input: CheckerInput): Promise<Finding[]> {
  const { inventory, projectPath } = input;
  const offenders: string[] = [];
  for (const page of inventory.pages) {
    if (page.kind !== 'list') continue;
    const abs = path.resolve(projectPath, page.file);
    const source = await readText(abs);
    if (!source) continue;
    // Accept both the bare <DataTable> and the responsive wrapper
    // <ResponsiveDataTable> (the scaffold-component baseline) as the customisation-ui
    // table — only a raw <table> with neither is an offender.
    const usesDataTable = /<(?:Responsive)?DataTable\b/.test(source);
    const usesRawTable = /<table\b/.test(source);
    if (usesRawTable && !usesDataTable) offenders.push(page.file);
  }
  if (offenders.length === 0) return [makeOk('DEV-UI-016')];
  return [
    makeWarn(
      'DEV-UI-016',
      { pages: offenders.join(',') },
      "List pages must use `<DataTable>` from `@/components/ui/DataTable` (customisation-ui baseline). Raw `<table>` skips the SmartStack search/pagination/sorting and breaks theme cohesion. Re-run scaffold-component with `--overwrite` for each listed page.",
      { fixSkill: 'frontend-component', fixPhaseKey: 'frontend', autoFixable: true },
    ),
  ];
}

// ─── DEV-UI-017 — generated CSS token classes exist in index.css ──────────

async function checkDevUi017(input: CheckerInput): Promise<Finding[]> {
  const { inventory, projectPath } = input;
  const indexCssPath = path.resolve(projectPath, 'src', 'index.css');
  const indexCss = (await fileExists(indexCssPath)) ? await readText(indexCssPath) : '';
  // Build a set of declared utility class names: `.input { ... }`, `.btn-primary { ... }`, …
  const declared = new Set<string>();
  const declRe = /^\s*\.([a-zA-Z][\w-]*)\s*[\{,]/gm;
  let m: RegExpExecArray | null;
  while ((m = declRe.exec(indexCss)) !== null) declared.add(m[1]);

  // Tokens used by the generated templates whose CSS lives in index.css. Other
  // class names (Tailwind utilities, framework-provided) are not checked.
  const TRACKED = ['input', 'btn-primary', 'btn-secondary'];
  const missingByPage: Array<{ file: string; classes: string[] }> = [];
  for (const page of inventory.pages) {
    const abs = path.resolve(projectPath, page.file);
    const source = await readText(abs);
    if (!source) continue;
    const used = new Set<string>();
    const classNameRe = /className\s*=\s*"([^"]+)"/g;
    while ((m = classNameRe.exec(source)) !== null) {
      for (const cls of m[1].split(/\s+/)) {
        if (TRACKED.includes(cls)) used.add(cls);
      }
    }
    const missing = Array.from(used).filter((c) => !declared.has(c));
    if (missing.length > 0) missingByPage.push({ file: page.file, classes: missing });
  }
  if (missingByPage.length === 0) return [makeOk('DEV-UI-017')];
  return missingByPage.map((p) =>
    makeWarn(
      'DEV-UI-017',
      { file: p.file, classes: p.classes.join(',') },
      `Page uses utility classes (\`${p.classes.join('`, `')}\`) that are not declared in src/index.css. Re-run scaffold-theme to inject the missing helper classes — without them, inputs and buttons render unstyled.`,
      { file: p.file, fixSkill: 'frontend-theme', fixPhaseKey: 'frontend', autoFixable: true },
    ),
  );
}

// ─── DEV-UI-018 — Barrel exports resolve to existing files ────────────────
// Catches the class of bug where `src/components/<area>/index.ts` re-exports
// a sibling module that was renamed or deleted. Vite serves a 404 for the
// missing module → the barrel cannot be transformed → every dynamic import
// that traverses it cascades into ChunkLoadError on the parent bundle.
// DEV-UI-003 only covers registry files; this rule covers generic barrels.

const BARREL_REEXPORT_RE = /export\s*(?:\*|\{[^}]*\})\s*from\s*['"`](\.\/?[^'"`]+)['"`]/g;

async function discoverBarrels(projectPath: string): Promise<string[]> {
  const patterns = [
    'src/components/**/index.ts',
    'src/pages/**/index.ts',
    'src/hooks/**/index.ts',
    'src/utils/**/index.ts',
    'src/services/**/index.ts',
    'src/features/**/index.ts',
  ];
  const out = new Set<string>();
  for (const pat of patterns) {
    for (const f of await findFiles(pat, { cwd: projectPath })) {
      const rel = path.relative(projectPath, f).replace(/\\/g, '/');
      // Exclude the registry aggregator — already covered by DEV-UI-003.
      if (rel === 'src/extensions/componentRegistry.generated.ts') continue;
      out.add(rel);
    }
  }
  return [...out].sort();
}

async function resolveBarrelExport(
  barrelAbsPath: string,
  importPath: string,
): Promise<string | null> {
  // Only relative imports are tracked — bare-module barrels (rare) bypass disk check.
  if (!importPath.startsWith('.')) return null;
  const target = path.resolve(path.dirname(barrelAbsPath), importPath);
  const candidates = [
    target,
    `${target}.tsx`,
    `${target}.ts`,
    path.join(target, 'index.tsx'),
    path.join(target, 'index.ts'),
  ];
  for (const c of candidates) {
    if (await fileExists(c)) return c;
  }
  return null;
}

async function checkDevUi018(input: CheckerInput): Promise<Finding[]> {
  const { args } = input;
  const projectPath = path.resolve(args.projectPath);
  const barrels = await discoverBarrels(projectPath);
  const broken: Finding[] = [];
  for (const rel of barrels) {
    const abs = path.join(projectPath, rel);
    const source = await readText(abs);
    BARREL_REEXPORT_RE.lastIndex = 0;
    let m: RegExpExecArray | null;
    while ((m = BARREL_REEXPORT_RE.exec(source)) !== null) {
      const importPath = m[1];
      const resolved = await resolveBarrelExport(abs, importPath);
      if (resolved !== null) continue;
      broken.push(makeErr(
        'DEV-UI-018',
        { broken: `${rel}→${importPath}` },
        "Either restore the missing file or delete the dead re-export line. A barrel `index.ts` that references a non-existent sibling makes Vite serve a 404 on the barrel itself, which cascades into ChunkLoadError on every dynamic import traversing it.",
        { file: rel, autoFixable: false },
      ));
    }
  }
  if (broken.length === 0) return [makeOk('DEV-UI-018')];
  return broken;
}

// ─── DEV-UI-022 — FK fields render via <EntityLookup>, never <input>/<select>
// Symmetric to backend DEV-DAT-008 (same-module FK constraints are real, not
// bare Guid). On the frontend, the symmetric guarantee is that the user
// interacts with a typed combobox over /api/{module}/{plural}/lookup — not a
// free-text Guid input that breaks on first paste and silently degrades UX.
//
// Detection: scan Form / Create / Edit pages for
//   <input ... name="xxxId">          // FK rendered as text field
//   <input ... id="xxxId">            // same, alternate attribute
//   <select ... value={...xxxId}>     // FK rendered as static dropdown
// The xxxId convention matches scaffold-component's field name convention
// (BA `entité.md` Rel: lines emit PascalCase FK columns → camelCase in TS).
//
// Whitelist: identifier-bearing fields that happen to end in "Id" but are NOT
// foreign-key references — `externalId` (third-party Id), `parentId` (raw
// self-reference, may be free-form), `guidId` (legacy alias). Extend at the
// top of the file; the test snapshot pins the default list.

const DEV_UI_022_FK_INPUT_RE = /<input\b[^>]*\b(?:name|id)\s*=\s*["']([A-Za-z]\w*Id)["']/g;
const DEV_UI_022_FK_SELECT_RE = /<select\b[^>]*\bvalue=\{[^}]*?\.([A-Za-z]\w*Id)\b[^}]*?\}/g;
const DEV_UI_022_WHITELIST = new Set(['externalId', 'parentId', 'guidId']);

async function checkDevUi022(input: CheckerInput): Promise<Finding[]> {
  const { inventory, projectPath } = input;
  const formPages = inventory.pages.filter((p) =>
    p.kind === 'form' || p.kind === 'create' || p.kind === 'edit',
  );
  if (formPages.length === 0) return [makeOk('DEV-UI-022', { note: 'no form pages on disk' })];

  const findings: Finding[] = [];
  for (const page of formPages) {
    const abs = path.join(projectPath, page.file);
    const source = await readText(abs);
    if (!source) continue;

    const offenders = new Set<string>();

    DEV_UI_022_FK_INPUT_RE.lastIndex = 0;
    let m: RegExpExecArray | null;
    while ((m = DEV_UI_022_FK_INPUT_RE.exec(source)) !== null) {
      const field = m[1];
      if (DEV_UI_022_WHITELIST.has(field)) continue;
      // Skip hidden inputs — Auth tokens, CSRF, … occasionally use ...Id naming
      // and are not user-facing.
      const tag = m[0];
      if (/type\s*=\s*["']hidden["']/.test(tag)) continue;
      offenders.add(field);
    }

    DEV_UI_022_FK_SELECT_RE.lastIndex = 0;
    while ((m = DEV_UI_022_FK_SELECT_RE.exec(source)) !== null) {
      const field = m[1];
      if (DEV_UI_022_WHITELIST.has(field)) continue;
      offenders.add(field);
    }

    for (const field of offenders) {
      findings.push(makeErr(
        'DEV-UI-022',
        { file: page.file, field, entity: page.entity },
        `FK field '${field}' is rendered as <input>/<select> instead of <EntityLookup>. ` +
        `Re-run scaffold-component for this page so the orchestrator (ba-develop Phase 3a) ` +
        `enriches the field with \`fkTo: { entity, module }\` from entité.md Rel: lines, ` +
        `and the generator emits <EntityLookup apiEndpoint="/api/{module}/{plural}/lookup" />. ` +
        `If the FK has no declared relation in entité.md, add 'Relations: ${page.entity ?? 'Source'} *→1 Target (FK ${field}, restrict)' ` +
        `to the entity definition, then re-audit.`,
        { file: page.file, fixSkill: 'frontend-component', fixPhaseKey: 'frontend', autoFixable: false },
      ));
    }
  }

  if (findings.length === 0) return [makeOk('DEV-UI-022')];
  return findings;
}

// ─── DEV-UI-023 — modern form controls use the theme-compliant primitives ───
// Dev-pipeline twin of ui-polish R26 (and symmetric to DEV-UI-022 for FKs): a
// date field must render via <DateInput> and an enum/list field via
// <EnumSelect>/<MultiSelect> — not a native <input type="date"> or <select>,
// whose browser-chrome widgets ignore the theme (corners, surface, dark mode).
// WARNING (non-blocking, anti-gate): the swap needs the orchestrator to populate
// options[]/multiple from entité.md, so it routes back to ba-develop Phase 3a
// rather than failing the build. FK <select> (value references a *Id field) is
// DEV-UI-022's domain (ERROR) and is skipped here to avoid double-reporting.

const DEV_UI_023_DATE_RE = /<input\b[^>]*?\btype\s*=\s*["'](datetime-local|date)["'][^>]*?>/g;
const DEV_UI_023_SELECT_RE = /<select\b[^>]*?>/g;
const DEV_UI_023_FK_VALUE_RE = /\bvalue=\{[^}]*\b[A-Za-z]\w*Id\b[^}]*\}/;

async function checkDevUi023(input: CheckerInput): Promise<Finding[]> {
  const { inventory, projectPath } = input;
  const formPages = inventory.pages.filter((p) =>
    p.kind === 'form' || p.kind === 'create' || p.kind === 'edit',
  );
  if (formPages.length === 0) return [makeOk('DEV-UI-023', { note: 'no form pages on disk' })];

  const findings: Finding[] = [];
  for (const page of formPages) {
    const abs = path.join(projectPath, page.file);
    const source = await readText(abs);
    if (!source) continue;

    // Native date / datetime inputs → <DateInput>.
    DEV_UI_023_DATE_RE.lastIndex = 0;
    let m: RegExpExecArray | null;
    while ((m = DEV_UI_023_DATE_RE.exec(source)) !== null) {
      findings.push(makeWarn(
        'DEV-UI-023',
        { file: page.file, control: `input[type=${m[1]}]`, entity: page.entity },
        `A native <input type="${m[1]}"> renders a browser-chrome calendar that ignores the theme. ` +
        `Use <DateInput> from @/components/ui/DateInput (scaffold-ui-primitives) — scaffold-component emits it automatically for date/datetime fields.`,
        { file: page.file, fixSkill: 'frontend-component', fixPhaseKey: 'frontend', autoFixable: false },
      ));
    }

    // Native <select> → <EnumSelect>/<MultiSelect> (skip FK selects — DEV-UI-022's domain).
    DEV_UI_023_SELECT_RE.lastIndex = 0;
    while ((m = DEV_UI_023_SELECT_RE.exec(source)) !== null) {
      const tag = m[0];
      if (DEV_UI_023_FK_VALUE_RE.test(tag)) continue;
      const isMulti = /\bmultiple\b/.test(tag);
      const want = isMulti ? 'MultiSelect' : 'EnumSelect';
      findings.push(makeWarn(
        'DEV-UI-023',
        { file: page.file, control: isMulti ? 'select[multiple]' : 'select', entity: page.entity },
        `A native <${isMulti ? 'select multiple' : 'select'}> renders a browser-chrome dropdown that ignores the theme. ` +
        `Use <${want}> from @/components/ui/${want} (scaffold-ui-primitives). Populate the field's \`options[]\`${isMulti ? ' and `multiple: true`' : ''} in ba-develop Phase 3a (from entité.md enumerations) so scaffold-component emits it automatically.`,
        { file: page.file, fixSkill: 'frontend-component', fixPhaseKey: 'frontend', autoFixable: false },
      ));
    }
  }

  if (findings.length === 0) return [makeOk('DEV-UI-023')];
  return findings;
}

// ─── Dispatcher ───────────────────────────────────────────────────────────

const CHECKERS: Record<string, (input: CheckerInput) => Promise<Finding[]>> = {
  'DEV-UI-001': checkDevUi001,
  'DEV-UI-002': checkDevUi002,
  'DEV-UI-003': checkDevUi003,
  'DEV-UI-004': checkDevUi004,
  'DEV-UI-005': checkDevUi005,
  'DEV-UI-006': checkDevUi006,
  'DEV-UI-007': checkDevUi007,
  'DEV-UI-008': checkDevUi008,
  'DEV-UI-009': checkDevUi009,
  'DEV-UI-010': checkDevUi010,
  'DEV-UI-011': checkDevUi011,
  'DEV-UI-012': checkDevUi012,
  'DEV-UI-013': checkDevUi013,
  'DEV-UI-014': checkDevUi014,
  'DEV-UI-015': checkDevUi015,
  'DEV-UI-016': checkDevUi016,
  'DEV-UI-017': checkDevUi017,
  'DEV-UI-018': checkDevUi018,
  'DEV-UI-022': checkDevUi022,
  'DEV-UI-023': checkDevUi023,
};

export async function audit(args: AuditDevFrontendArgs): Promise<AuditReport> {
  const projectPath = path.resolve(args.projectPath);
  const inventory = args.inventory
    ? await readJson<FrontendInventory>(path.resolve(args.inventory))
    : await buildInventory(projectPath);
  const prdSlice = await loadPrdSlice(args.prdSlice);

  const wantRules = args.rules.length === 0
    ? Object.keys(CHECKERS)
    : args.rules.filter((r) => CHECKERS[r]);

  const findings: Finding[] = [];
  const input: CheckerInput = { args, prdSlice, inventory, projectPath };
  for (const ruleId of wantRules) {
    const checker = CHECKERS[ruleId];
    try {
      const hits = await checker(input);
      findings.push(...hits);
    } catch (err) {
      findings.push(makeErr(
        ruleId,
        { error: err instanceof Error ? err.message : String(err) },
        `Checker for ${ruleId} threw an exception. This is an audit bug, not a code defect — investigate the checker logic.`,
        { autoFixable: false },
      ));
    }
  }

  const counts = { errors: 0, warnings: 0, oks: 0 };
  const byRule: Record<string, number> = {};
  for (const f of findings) {
    if (f.severity === 'err') counts.errors++;
    else if (f.severity === 'warn') counts.warnings++;
    else counts.oks++;
    byRule[f.code] = (byRule[f.code] ?? 0) + 1;
  }

  return {
    scope: 'devFrontend',
    applicationCode: args.appCode,
    moduleCode: args.moduleCode,
    projectPath,
    filesInspected: inventory.pages.length,
    findings,
    counts,
    byRule,
  };
}

export { CHECKERS };
