#!/usr/bin/env python3
"""Deterministic preflight gate for interactive HTML files.

Uses only stdlib html.parser. Output is a JSON report:
  {"pass": bool, "failures": [], "warnings": []}

WCAG validators live in ``wcag_checks.py`` (extracted PR1 of
docs/plan-wcag-2.1-aa-hardening.md) so the same checks serve all Canvas
content surfaces. This module is the interactive-activity deploy gate:
it collects HTML files, runs the shared parser, and emits the gate
report. Behavior is byte-for-byte unchanged from before the extraction.
"""

import argparse
import json
import sys
from pathlib import Path

# Shared WCAG validators. One-directional import: wcag_checks never imports
# back from this module.
from wcag_checks import (  # noqa: F401  (issue/contrast_* re-exported for callers + tests)
    VOID_TAGS,
    InteractiveA11yParser,
    WCAGContentParser,
    contrast_issue,
    contrast_ratio,
    issue,
    parse_color,
    parse_style,
    relative_luminance,
)


PREFLIGHT_PASS_MESSAGE = (
    "Preflight passed (subset of WCAG 2.1 AA; manual review still required for "
    "visible focus indicators, computed contrast, accessible names on role-elements, "
    "dialog focus trap, prefers-reduced-motion)."
)


def check_file(path):
    parser = InteractiveA11yParser(path)
    parser.feed(path.read_text(encoding="utf-8"))
    parser.close()
    parser.finalize()
    return parser.failures, parser.warnings


def collect_html_files(paths):
    files = []
    for raw in paths:
        path = Path(raw)
        if path.is_dir():
            files.extend(sorted(p for p in path.rglob("*.html") if p.is_file()))
        elif path.is_file():
            files.append(path)
    return files


def run(paths):
    failures = []
    warnings = []
    files = collect_html_files(paths)
    if not files:
        failures.append(issue(Path("."), "NO_HTML", "No HTML files found"))
    for path in files:
        file_failures, file_warnings = check_file(path)
        failures.extend(file_failures)
        warnings.extend(file_warnings)
    return {"pass": not failures, "failures": failures, "warnings": warnings}


def main():
    parser = argparse.ArgumentParser(description="Run deterministic preflight checks on interactive HTML files.")
    parser.add_argument("paths", nargs="+", help="HTML file or directory to check")
    args = parser.parse_args()

    report = run(args.paths)
    print(json.dumps(report, indent=2))
    if not report["pass"]:
        sys.exit(1)
    print(PREFLIGHT_PASS_MESSAGE, file=sys.stderr)


if __name__ == "__main__":
    main()
