#!/usr/bin/env node
// Fails when a raw colour, px font-size, or ad-hoc breakpoint appears outside
// the token layer. A rule nobody checks is a suggestion — wire this into
// `pnpm run verify`.
//
// ESCAPE HATCH — `token-gap:`. Some legacy values have no token yet, and only
// `design-system-keeper` may add one. Without an escape, an agent told both
// "keep the site identical" and "get the gate green" has to break one of them,
// and tasks 10 and 11 both broke the first: `#e5eeeb` became `var(--paper)`,
// diff-added green became `var(--accent)` purple. Substituting a near-miss
// token is a silent redesign; it is worse than a raw value, because the raw
// value is at least honest about what it is.
//
// So: mark the line, keep the true value, stay green.
//
//   /* token-gap: no --step-* covers 12px; owner design-system-keeper */
//   font-size: 12px;
//
// Marked values are counted and listed on every run — they are a visible debt
// queue, not a way to make the finding disappear. The marker needs a reason;
// a bare `token-gap:` does not count.
//
// Usage: node .agents/scripts/check-tokens.mjs [srcDir]

import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join, extname } from 'node:path';

// lint-staged appends staged file paths; a bare run sweeps `src`.
const ARGS = process.argv.slice(2);
const TOKEN_FILES = ['tokens.css', 'base.css'];
const ALLOWED_BREAKPOINTS = ['560px', '800px', '1100px', '1600px', '2200px'];

const walk = (dir) =>
  readdirSync(dir).flatMap((name) => {
    const path = join(dir, name);
    return statSync(path).isDirectory() ? walk(path) : [path];
  });

const targets = ARGS.length
  ? ARGS.flatMap((arg) => (statSync(arg).isDirectory() ? walk(arg) : [arg]))
  : walk('src');

const findings = [];
const gaps = [];

// A finding is waived when its own line, or the line above it, carries a
// `token-gap:` marker with a reason after the colon.
const MARKER = /token-gap:([^\n]*)/;
// The reason is what is left after the marker once the comment terminator and
// punctuation are stripped. `/* token-gap: */` is not a reason.
const reason = (line) => {
  const found = MARKER.exec(line ?? '');
  if (!found) return null;
  const text = found[1]
    .replace(/\*\/\s*$/, '')
    .replace(/[\s*/]+$/, '')
    .trim();
  return /[a-z0-9]/i.test(text) ? [null, text] : null;
};
const waiver = (lines, index) =>
  reason(lines[index]) || (index > 0 ? reason(lines[index - 1]) : null);

for (const path of targets) {
  if (!['.astro', '.css'].includes(extname(path))) continue;
  if (TOKEN_FILES.some((allowed) => path.endsWith(allowed))) continue;

  const lines = readFileSync(path, 'utf8').split('\n');
  lines.forEach((line, index) => {
    const at = `${path}:${index + 1}`;
    const waived = waiver(lines, index);
    const record = (finding) => {
      if (waived) gaps.push(`${at}: ${finding.slice(at.length + 2)} [${waived[1]}]`);
      else findings.push(finding);
    };

    // Raw hex — the drifted-palette failure mode this whole layer exists to stop.
    const hex = line.match(/#[0-9a-fA-F]{3,8}\b/g);
    if (hex) record(`${at}: raw hex ${hex.join(', ')} — use a token from tokens.css`);

    // rgb()/hsl() literals are the same problem wearing a different hat.
    if (/\b(rgba?|hsla?)\(\s*\d/.test(line)) record(`${at}: raw colour function — use a token`);

    // Hard-coded font sizes bypass the type scale.
    const fontSize = line.match(/font-size:\s*\d+(\.\d+)?px/);
    if (fontSize) record(`${at}: hard-coded ${fontSize[0]} — use var(--step-*)`);

    // Ad-hoc breakpoints are how sixteen of them accumulated last time.
    const media = line.match(/@media[^{]*?\(\s*(?:max|min)-width:\s*(\d+px)/);
    if (media && !ALLOWED_BREAKPOINTS.includes(media[1]))
      record(
        `${at}: breakpoint ${media[1]} is not a named one (${ALLOWED_BREAKPOINTS.join(', ')})`,
      );
  });
}

if (gaps.length) {
  console.log(`token check: ${gaps.length} marked token-gap(s) awaiting design-system-keeper:\n`);
  gaps.forEach((gap) => console.log(`  ${gap}`));
  console.log('');
}

if (findings.length) {
  console.error(`token check failed — ${findings.length} finding(s):\n`);
  findings.forEach((finding) => console.error(`  ${finding}`));
  process.exit(1);
}

import { existsSync } from 'node:fs';
import { basename } from 'node:path';

if (existsSync('dist')) {
  const builtCss = walk('dist').filter((p) => p.endsWith('.css'));
  const tokensBuilt = builtCss.find((p) => /[\\/]tokens\.[^\\/]+\.css$/.test(p));

  if (!tokensBuilt) {
    console.error('token check failed — tokens.css was not built into dist/');
    process.exit(1);
  }

  const tokensContent = readFileSync(tokensBuilt, 'utf8');
  if (!tokensContent.includes('#527f9f')) {
    console.error(
      'token check failed — built tokens.css does not contain the canonical --blue value #527f9f',
    );
    process.exit(1);
  }

  const htmlFiles = walk('dist').filter(
    (p) =>
      p.endsWith('.html') &&
      !p.includes('/hands-on/') &&
      !p.includes('\\hands-on\\') &&
      !p.includes('/submitted-skills/') &&
      !p.includes('\\submitted-skills\\'),
  );

  const tokenChunkName = basename(tokensBuilt);
  for (const html of htmlFiles) {
    const content = readFileSync(html, 'utf8');
    if (!content.includes(tokenChunkName)) {
      console.error(
        `token check failed — ${html} does not load the token layer (${tokenChunkName})`,
      );
      process.exit(1);
    }
  }
}

console.log('token check passed');
