#!/usr/bin/env python3
"""machine_check.py — the machine half of an audit, from the Interfaces Institute audit kit.

It loads each page in a real browser at three widths and reports what a machine
can know: axe-core's WCAG 2.2 A/AA rules, plus probes axe does not make. It
presses Tab for real and counts the stops before the main content, checks that
each focused element is visibly marked and not hidden under a sticky bar, and
measures target sizes, reflow at 320 px and text in another script without a
language. It cannot tell you whether the page is any good to use. That is the
other half of the audit, and it is a person's job.

    pip install playwright && playwright install chromium
    python3 machine_check.py https://example.org/ https://example.org/about/ --out results.json

Licence: MIT. https://interfaces.institute/audits/kit/
"""
import argparse
import json
import sys
from datetime import datetime, timezone

from playwright.sync_api import sync_playwright

AXE = 'https://cdnjs.cloudflare.com/ajax/libs/axe-core/4.10.2/axe.min.js'
AXE_TAGS = ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa', 'wcag22aa']
WIDTHS = [320, 375, 1280]
MAX_TABS = 80

# Probes that run in the page. Each returns plain data; the judgement is the reader's.
PROBES = r"""
() => {
  const vis = (e) => { const r = e.getBoundingClientRect(), s = getComputedStyle(e);
    return r.width > 0 && r.height > 0 && s.visibility !== 'hidden' && s.display !== 'none'; };
  const name = (e) => (e.getAttribute('aria-label') || (e.getAttribute('aria-labelledby') || '').split(' ')
    .map((id) => document.getElementById(id)?.textContent || '').join(' ') || [...(e.labels || [])].map((l) => l.textContent).join(' ')
    || e.getAttribute('placeholder') || e.textContent || e.getAttribute('title')
    || e.getAttribute('alt') || e.value || '').trim().replace(/\s+/g, ' ');
  const sel = (e) => e.tagName.toLowerCase() + (e.id ? '#' + e.id : '') +
    (e.classList.length ? '.' + [...e.classList].slice(0, 2).join('.') : '');
  const heads = [...document.querySelectorAll('h1,h2,h3,h4,h5,h6,[role=heading]')].filter(vis)
    .map((h) => ({ level: +(h.getAttribute('aria-level') || h.tagName[1]), text: name(h).slice(0, 80) }));
  const skipped = heads.filter((h, i) => i > 0 && h.level > heads[i - 1].level + 1)
    .map((h) => h.text);
  const landmarks = [...document.querySelectorAll('header,nav,main,aside,footer,[role=banner],[role=navigation],[role=main],[role=complementary],[role=contentinfo],[role=search],form[aria-label]')]
    .map((e) => e.getAttribute('role') || e.tagName.toLowerCase());
  const controls = [...document.querySelectorAll('a[href],button,input:not([type=hidden]),select,textarea,[role=button],[role=link],[role=combobox],[role=option],[role=tab],[tabindex]:not([tabindex="-1"])')].filter(vis);
  const small = controls.map((e) => { const r = e.getBoundingClientRect();
      return { el: sel(e), name: name(e).slice(0, 40), w: Math.round(r.width), h: Math.round(r.height),
               inline: getComputedStyle(e).display === 'inline' && e.closest('p,li,td,dd') !== null }; })
    .filter((t) => (t.w < 24 || t.h < 24) && !t.inline);
  const unnamed = controls.filter((e) => !name(e)).map(sel);
  // Text in a non-Latin script whose nearest lang is a Latin-script language.
  const scripts = /[Ͱ-ϿЀ-ӿ֐-׿؀-ۿऀ-ॿ฀-๿぀-ヿ㐀-鿿가-힯]/;
  const latinLangs = /^(en|fr|de|es|it|pt|nl|sv|da|no|fi|pl|cs|ro|hu|tr)/i;
  const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
  const foreign = []; let n;
  while ((n = walker.nextNode()) && foreign.length < 30) {
    const t = n.textContent.trim(); if (!t || !scripts.test(t)) continue;
    const host = n.parentElement; if (!host || !vis(host)) continue;
    const lang = host.closest('[lang]')?.getAttribute('lang') || '';
    if (!lang || latinLangs.test(lang)) foreign.push({ text: t.slice(0, 40), lang, el: sel(host) });
  }
  const imgs = [...document.querySelectorAll('img')].filter((i) => !i.hasAttribute('alt')).map(sel);
  const svgs = [...document.querySelectorAll('svg')].filter((s) => vis(s) && !s.closest('[aria-hidden=true]')
    && s.getAttribute('aria-hidden') !== 'true' && !s.getAttribute('aria-label') && !s.querySelector('title')
    && !s.closest('a,button')?.textContent.trim()).length;
  const skip = [...document.querySelectorAll('a[href^="#"]')].find((a) => /skip|main content|jump/i.test(a.textContent));
  return {
    title: document.title, lang: document.documentElement.lang || null,
    h1: heads.filter((h) => h.level === 1).length, headings: heads.slice(0, 40), skipped_levels: skipped,
    landmarks: [...new Set(landmarks)], main: !!document.querySelector('main,[role=main]'),
    skip_link: skip ? { text: name(skip), target: skip.getAttribute('href'),
      target_exists: !!document.getElementById(skip.getAttribute('href').slice(1)) } : null,
    controls: controls.length, unnamed_controls: unnamed.slice(0, 30), small_targets: small.slice(0, 30),
    small_targets_n: small.length, imgs_without_alt: imgs, unlabelled_svgs: svgs,
    text_in_other_script_without_lang: foreign,
    overflow_x: document.documentElement.scrollWidth > window.innerWidth + 1,
    scroll_width: document.documentElement.scrollWidth,
  };
}
"""

# One real Tab press: what has focus, is it marked, is it under something fixed.
FOCUS = r"""
() => {
  const e = document.activeElement; if (!e || e === document.body) return null;
  const s = getComputedStyle(e), r = e.getBoundingClientRect();
  const marked = (s.outlineStyle !== 'none' && parseFloat(s.outlineWidth) > 0) || s.boxShadow !== 'none';
  const cx = r.left + r.width / 2, cy = r.top + Math.min(r.height / 2, 8);
  const top = document.elementFromPoint(Math.max(0, Math.min(cx, innerWidth - 1)), Math.max(0, Math.min(cy, innerHeight - 1)));
  // Covered: the topmost element at the focus point is not the focused one, and
  // it belongs to something fixed or sticky (a header, a cookie bar, a toolbar).
  let covered = false;
  if (top && top !== e && !e.contains(top) && !top.contains(e)) {
    for (let x = top; x; x = x.parentElement) {
      if (['fixed', 'sticky'].includes(getComputedStyle(x).position)) { covered = true; break; }
    }
  }
  const label = (e.getAttribute('aria-label') || [...(e.labels || [])].map((l) => l.textContent).join(' ') || e.textContent || e.getAttribute('alt') || e.value || '').trim().replace(/\s+/g, ' ').slice(0, 50);
  return { el: e.tagName.toLowerCase() + (e.id ? '#' + e.id : ''), name: label, role: e.getAttribute('role') || '',
           marked, covered: !!covered, in_main: !!e.closest('main,[role=main]'), offscreen: r.bottom < 0 || r.top > innerHeight };
}
"""


def tab_walk(page):
    stops, first_main = [], None
    page.keyboard.press('Escape')
    page.evaluate('() => { document.activeElement?.blur(); window.scrollTo(0, 0); }')
    for i in range(1, MAX_TABS + 1):
        page.keyboard.press('Tab')
        f = page.evaluate(FOCUS)
        if f is None:
            break
        if stops and f['el'] == stops[0]['el'] and f['name'] == stops[0]['name']:
            break  # wrapped round
        stops.append(f)
        if first_main is None and f['in_main']:
            first_main = i
    return {
        'stops_walked': len(stops), 'first_stop_in_main': first_main,
        'unmarked': [s for s in stops if not s['marked']][:15],
        'covered_by_fixed_or_sticky': [s for s in stops if s['covered']][:15],
        'first_ten': [f"{s['el']} “{s['name']}”" for s in stops[:10]],
    }


def check(url, browser):
    out = {'url': url, 'widths': {}}
    for w in WIDTHS:
        ctx = browser.new_context(viewport={'width': w, 'height': 800 if w > 600 else 740},
                                  reduced_motion='reduce')
        page = ctx.new_page()
        page.goto(url, wait_until='networkidle', timeout=45000)
        r = {'probes': page.evaluate(PROBES)}
        if w in (375, 1280):
            r['keyboard'] = tab_walk(page)
        if w == 1280:
            page.add_script_tag(url=AXE)
            res = page.evaluate('(tags) => axe.run(document, { runOnly: { type: "tag", values: tags } })', AXE_TAGS)
            r['axe'] = {
                'version': res.get('testEngine', {}).get('version'),
                'violations': [{'id': v['id'], 'impact': v['impact'], 'help': v['help'],
                                'tags': [t for t in v['tags'] if t.startswith('wcag')], 'nodes': len(v['nodes']),
                                'examples': [n['target'][0] if isinstance(n['target'][0], str) else str(n['target'][0])
                                             for n in v['nodes'][:3]]}
                               for v in res['violations']],
                'incomplete': [{'id': v['id'], 'help': v['help'], 'nodes': len(v['nodes'])} for v in res['incomplete']],
                'passes': len(res['passes']),
            }
            # 200% text: does anything get cut off or overflow?
            page.add_style_tag(content='html{font-size:200% !important}')
            r['text_200_overflow_x'] = page.evaluate('() => document.documentElement.scrollWidth > innerWidth + 1')
            # WCAG 1.4.12 text spacing
            page.add_style_tag(content='*{line-height:1.5 !important;letter-spacing:.12em !important;word-spacing:.16em !important}p{margin-bottom:2em !important}')
            r['text_spacing_overflow_x'] = page.evaluate('() => document.documentElement.scrollWidth > innerWidth + 1')
        out['widths'][w] = r
        ctx.close()
    return out


def main():
    ap = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
    ap.add_argument('urls', nargs='+')
    ap.add_argument('--out', default='results.json')
    ap.add_argument('--engine', choices=['chromium', 'webkit'], default='chromium')
    a = ap.parse_args()
    report = {'run': datetime.now(timezone.utc).isoformat(timespec='seconds'), 'engine': a.engine,
              'axe': AXE, 'pages': []}
    with sync_playwright() as p:
        browser = getattr(p, a.engine).launch()
        for u in a.urls:
            print('checking', u, file=sys.stderr)
            try:
                report['pages'].append(check(u, browser))
            except Exception as e:  # one bad page does not lose the rest
                report['pages'].append({'url': u, 'error': str(e)})
        browser.close()
    with open(a.out, 'w', encoding='utf-8') as f:
        json.dump(report, f, ensure_ascii=False, indent=1)
    print('written', a.out, file=sys.stderr)


if __name__ == '__main__':
    main()
