/**
 * Browser driving: navigate each configured route at each configured viewport
 * and run a real axe-core pass against the rendered DOM.
 *
 * `playwright-core` and `@axe-core/playwright` are imported dynamically so the
 * shared runner can live in fe-libs without dragging a browser automation
 * dependency into every consumer of the component library. Consuming repos
 * declare them as devDependencies; a missing one is a loud, actionable error.
 */

import { partitionNodes, flattenViolations } from './allowlist';
import {
  materializeCookies,
  materializeLocalStorage,
  matchesGraphqlEndpoint,
  respondToGraphql,
  seedLocalStorageScript,
} from './fixtures';
import type { AxeViolationLike } from './allowlist';
import type { RunningApp } from './server';
import type { AuditReport, FixtureSpec, ResolvedConfig, RouteResult } from './types';

/* eslint-disable @typescript-eslint/no-explicit-any -- dynamically imported
   third-party modules have no static types available inside this script. */
type AnyRecord = Record<string, any>;

const MISSING_DEP_HINT =
  'Add them to the repo devDependencies:\n' +
  '    bun add -d @playwright/test @axe-core/playwright\n' +
  '    bunx playwright install --with-deps chromium';

async function loadPlaywright(): Promise<AnyRecord> {
  for (const specifier of ['playwright', 'playwright-core', '@playwright/test']) {
    try {
      const mod = (await import(specifier)) as AnyRecord;
      if (mod?.chromium) return mod.chromium as AnyRecord;
    } catch {
      /* try the next specifier */
    }
  }
  throw new Error(`[a11y-audit] Cannot resolve Playwright.\n  ${MISSING_DEP_HINT}`);
}

type AxeBuilderCtor = new (options: { page: AnyRecord }) => {
  withTags: (tags: string[]) => { analyze: () => Promise<AnyRecord> };
};

async function loadAxeBuilder(): Promise<AxeBuilderCtor> {
  try {
    const mod = (await import('@axe-core/playwright')) as AnyRecord;
    return (mod.default ?? mod) as AxeBuilderCtor;
  } catch (error) {
    throw new Error(
      `[a11y-audit] Cannot resolve @axe-core/playwright (${(error as Error).message}).\n  ` +
        MISSING_DEP_HINT,
      { cause: error }
    );
  }
}

async function loadAxeVersion(): Promise<string> {
  try {
    const mod = (await import('axe-core')) as AnyRecord;
    return (mod.default?.version ?? mod.version ?? 'unknown') as string;
  } catch {
    return 'unknown';
  }
}

interface DomSnapshot {
  textLength: number;
  elementCount: number;
}

async function snapshotDom(page: AnyRecord): Promise<DomSnapshot> {
  return (await page.evaluate(() => ({
    textLength: (document.body?.innerText ?? '').trim().length,
    elementCount: document.querySelectorAll('*').length,
  }))) as DomSnapshot;
}

/**
 * Poll until the rendered DOM stops changing for `quietMs`, or `timeoutMs`
 * elapses. Returns the final snapshot and whether it actually went quiet.
 *
 * This is what makes the gate reproducible on a shell that paints a splash
 * before it paints the page.
 */
async function waitForStableDom(
  page: AnyRecord,
  quietMs: number,
  timeoutMs: number
): Promise<{ snapshot: DomSnapshot; settled: boolean }> {
  const pollMs = 250;
  const deadline = Date.now() + timeoutMs;
  let previous = await snapshotDom(page);
  let quietSince = Date.now();

  while (Date.now() < deadline) {
    await page.waitForTimeout(pollMs);
    const current = await snapshotDom(page);
    if (
      current.textLength !== previous.textLength ||
      current.elementCount !== previous.elementCount
    ) {
      previous = current;
      quietSince = Date.now();
      continue;
    }
    previous = current;
    if (Date.now() - quietSince >= quietMs) return { snapshot: current, settled: true };
  }
  return { snapshot: previous, settled: false };
}

/** Run the full audit. Throws on navigation failure — never silently skips a route. */
export async function runAudit(
  config: ResolvedConfig,
  app: Pick<RunningApp, 'baseUrl' | 'resolveAsset'>,
  now: Date = new Date()
): Promise<AuditReport> {
  const { baseUrl, resolveAsset } = app;
  const chromium = await loadPlaywright();
  const AxeBuilder = await loadAxeBuilder();
  const axeVersion = await loadAxeVersion();

  const browser = await chromium.launch({
    args: ['--no-sandbox', '--disable-dev-shm-usage', '--disable-gpu'],
  });
  const results: RouteResult[] = [];
  const usedEntries = new Set<number>();
  const navigationErrors: string[] = [];

  /**
   * Fresh page with request routing applied — used for the first try and every
   * retry. With a fixture, its session is seeded before any page script runs
   * and its GraphQL endpoints are answered from the fixture (recording any
   * operation it has no answer for in `unmocked`).
   */
  const openPage = async (
    context: AnyRecord,
    fixture: FixtureSpec | undefined,
    unmocked: Set<string>
  ): Promise<AnyRecord> => {
    if (fixture?.cookies) {
      await context.addCookies(
        materializeCookies(fixture).map((cookie) => ({
          ...cookie,
          url: baseUrl,
        }))
      );
    }
    const page = await context.newPage();
    if (fixture?.localStorage) {
      await page.addInitScript(seedLocalStorageScript, {
        origin: new URL(baseUrl).origin,
        entries: materializeLocalStorage(fixture),
      });
    }
    if (config.blockExternalRequests || resolveAsset || fixture?.graphql) {
      await page.route('**/*', (route: AnyRecord) => {
        const request = route.request();
        const requestUrl: string = request.url();
        const isOwnOrigin = requestUrl.startsWith(baseUrl);

        // Fixture GraphQL first: on any origin, a matching endpoint is answered
        // from the fixture and never reaches a live gateway.
        if (fixture?.graphql && matchesGraphqlEndpoint(requestUrl, fixture)) {
          if (request.method() === 'OPTIONS') {
            void route.fulfill({
              status: 204,
              headers: {
                'access-control-allow-origin': new URL(baseUrl).origin,
                'access-control-allow-credentials': 'true',
                'access-control-allow-methods': 'GET, POST, OPTIONS',
                'access-control-allow-headers': '*',
              },
              body: '',
            });
            return;
          }
          const answer = respondToGraphql(
            fixture,
            request.method() as string,
            requestUrl,
            (request.postData() as string | null) ?? null
          );
          answer.unmocked.forEach((name) => unmocked.add(name));
          void route.fulfill({
            status: answer.status,
            contentType: 'application/json',
            headers: {
              'access-control-allow-origin': new URL(baseUrl).origin,
              'access-control-allow-credentials': 'true',
            },
            body: answer.body,
          });
          return;
        }

        // Serve the build's own files straight from disk. Chromium never opens
        // a socket for them, so a spurious network-change notification cannot
        // cancel a hundred in-flight chunk loads and leave the shell blank.
        if (isOwnOrigin && resolveAsset) {
          const asset = resolveAsset(new URL(requestUrl).pathname);
          if (asset) {
            void route.fulfill({
              status: 200,
              contentType: asset.contentType,
              headers: { 'cache-control': 'no-store' },
              body: asset.body,
            });
            return;
          }
          void route.fulfill({
            status: 404,
            contentType: 'text/plain',
            body: 'Not found',
          });
          return;
        }

        // Deterministic DOM: nothing the audit sees depends on a live backend,
        // a CDN or the runner's network latency.
        if (isOwnOrigin || requestUrl.startsWith('data:') || !config.blockExternalRequests) {
          void route.continue();
          return;
        }
        void route.abort();
      });
    }
    return page;
  };

  // Every route gets its own browser context, so a fixture's seeded session
  // can never leak into the signed-out routes audited after it (or the other
  // way round), and route order cannot change what axe sees.
  const newContext = async (viewport: { width: number; height: number }): Promise<AnyRecord> =>
    browser.newContext({
      viewport: { width: viewport.width, height: viewport.height },
      // Deterministic rendering: no OS locale/timezone drift between the dev
      // machine and the CI runner changing what axe sees.
      locale: 'en-US',
      timezoneId: 'UTC',
      reducedMotion: 'reduce',
      // A service worker caching the shell across routes would make the audit
      // depend on which route ran first.
      serviceWorkers: 'block',
    });

  try {
    for (const viewport of config.viewports) {
      for (const route of config.routes) {
        const url = `${baseUrl}${route.path}`;
        const attemptFailures: string[] = [];
        let result: RouteResult | null = null;
        const fixture = route.fixture ? config.fixtures[route.fixture] : undefined;

        for (let attempt = 1; attempt <= config.routeAttempts && result === null; attempt += 1) {
          const context = await newContext(viewport);
          const unmocked = new Set<string>();
          const page = await openPage(context, fixture, unmocked);
          try {
            const response = await page.goto(url, {
              waitUntil: 'load',
              timeout: config.navigationTimeoutMs,
            });
            if (response && response.status() >= 400) {
              throw new Error(`HTTP ${response.status()}`);
            }
            if (route.waitForSelector) {
              await page.waitForSelector(route.waitForSelector, {
                timeout: config.navigationTimeoutMs,
              });
            }
            await page.waitForTimeout(route.settleMs ?? config.settleMs);

            const stability = await waitForStableDom(
              page,
              config.domQuietMs,
              config.navigationTimeoutMs
            );
            if (fixture && !route.allowRedirect) {
              const landed = new URL(page.url() as string).pathname.replace(/\/+$/, '') || '/';
              const expected = new URL(url).pathname.replace(/\/+$/, '') || '/';
              if (landed !== expected) {
                throw new Error(
                  `fixture "${route.fixture}" route ended on ${landed} instead of ${expected} — ` +
                    'the fixture did not produce the page, so auditing where it landed would be ' +
                    'a false pass' +
                    (unmocked.size > 0 ? ` (unmocked operations: ${[...unmocked].join(', ')})` : '')
                );
              }
            }
            const floor = route.minTextLength ?? config.minTextLength;
            if (stability.snapshot.textLength < floor) {
              throw new Error(
                `rendered only ${stability.snapshot.textLength} characters of text (floor is ` +
                  `${floor}) — the page never finished painting, so a clean axe result here ` +
                  'would be meaningless'
              );
            }

            const axeResults = (await new AxeBuilder({ page })
              .withTags(config.standard)
              .analyze()) as AnyRecord;

            const nodes = flattenViolations(axeResults.violations as AxeViolationLike[], {
              route: route.path,
              routeName: route.name,
              viewport: viewport.name,
            });
            const partition = partitionNodes(nodes, config.allowlist, config.failOn, now);
            partition.usedEntries.forEach((index) => usedEntries.add(index));

            result = {
              route: route.path,
              routeName: route.name,
              viewport: viewport.name,
              finalUrl: page.url(),
              blocking: partition.blocking,
              allowed: partition.allowed,
              advisory: partition.advisory,
              passCount: (axeResults.passes as unknown[]).length,
              incompleteCount: (axeResults.incomplete as unknown[]).length,
              renderedTextLength: stability.snapshot.textLength,
              domSettled: stability.settled,
              attempts: attempt,
              ...(route.fixture
                ? {
                    fixture: route.fixture,
                    unmockedOperations: [...unmocked].sort(),
                  }
                : {}),
            };
          } catch (error) {
            attemptFailures.push(`attempt ${attempt}: ${(error as Error).message}`);
          } finally {
            await page.close();
            await context.close();
          }
        }

        if (result === null) {
          navigationErrors.push(
            `${route.name} @ ${viewport.name} (${url}):\n      ${attemptFailures.join('\n      ')}`
          );
          continue;
        }
        if (result.attempts > 1) {
          console.warn(
            `[a11y-audit] ${route.name} @ ${viewport.name} needed ${result.attempts} attempts ` +
              `(${attemptFailures.join('; ')})`
          );
        }
        results.push(result);
      }
    }
  } finally {
    await browser.close();
  }

  if (navigationErrors.length > 0) {
    throw new Error(
      `[a11y-audit] ${navigationErrors.length} route(s) could not be loaded, so the audit is ` +
        'incomplete and cannot be treated as a pass:\n  - ' +
        navigationErrors.join('\n  - ')
    );
  }

  const staleAllowlistEntries = config.allowlist
    .map((entry, index) => ({ index, rule: entry.rule, reason: entry.reason }))
    .filter((entry) => !usedEntries.has(entry.index));

  const expiredAllowlistEntries = config.allowlist
    .map((entry, index) => ({
      index,
      rule: entry.rule,
      expires: entry.expires ?? '',
    }))
    .filter((entry) => {
      if (!entry.expires) return false;
      return now.getTime() > new Date(`${entry.expires}T23:59:59.999Z`).getTime();
    });

  return {
    name: config.name,
    generatedAt: now.toISOString(),
    baseUrl,
    standard: config.standard,
    failOn: config.failOn,
    axeVersion,
    blockExternalRequests: config.blockExternalRequests,
    routes: results,
    staleAllowlistEntries,
    expiredAllowlistEntries,
    totals: {
      blocking: results.reduce((sum, r) => sum + r.blocking.length, 0),
      allowed: results.reduce((sum, r) => sum + r.allowed.length, 0),
      advisory: results.reduce((sum, r) => sum + r.advisory.length, 0),
      routesAudited: results.length,
    },
  };
}
