#!/usr/bin/env python3
"""Verify CARBON specialist commands, grayscale profiles, WCAG, and ACR reporting."""

from __future__ import annotations

import json
import subprocess
import tempfile
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
LAUNCHER = ROOT / "bin" / "carbon-runtime"
REFERENCES = ROOT / "runtime" / "carbon" / "references"
DOMAIN_SKILLS = {
    "carbon-test",
    "carbon-functionality",
    "carbon-ui",
    "carbon-ux",
    "carbon-usability",
    "carbon-accessibility",
    "carbon-privacy",
    "carbon-security",
    "carbon-performance",
    "carbon-networking",
    "carbon-reliability",
    "carbon-compatibility",
    "carbon-content",
    "carbon-data",
    "carbon-api",
    "carbon-localization",
}


def jpeg_components(path: Path) -> int:
    data = path.read_bytes()
    for marker in (b"\xff\xc0", b"\xff\xc1", b"\xff\xc2"):
        index = data.find(marker)
        if index >= 0 and index + 9 < len(data):
            return data[index + 9]
    raise AssertionError(f"JPEG start-of-frame marker missing: {path}")


def render(root: Path, payload: dict) -> dict:
    result = subprocess.run(
        [str(LAUNCHER), "command-report", "render", "--root", str(root), "--payload-json", json.dumps(payload)],
        check=True,
        capture_output=True,
        text=True,
    )
    return json.loads(result.stdout)


def main() -> int:
    specialists = json.loads((REFERENCES / "specialists.json").read_text(encoding="utf-8"))
    domains = json.loads((REFERENCES / "testing-domains.json").read_text(encoding="utf-8"))
    wcag = json.loads((REFERENCES / "wcag22-criteria.json").read_text(encoding="utf-8"))
    acr_contract = json.loads((REFERENCES / "acr-reporting.json").read_text(encoding="utf-8"))
    assert specialists["schema"] == "carbon.specialists/v2"
    assert len(specialists["specialists"]) == 21
    assert "force grayscale at render time" in specialists["avatarPolicy"]
    assert "visible AI identity badge" in specialists["avatarPolicy"]
    assert domains["focusedCommand"] == "carbon-test"
    assert len(domains["domains"]) == 15
    assert {row["command"] for row in domains["domains"]} | {"carbon-test"} == DOMAIN_SKILLS
    assert len(wcag["criteria"]) == 55
    assert {row["level"] for row in wcag["criteria"]} == {"A", "AA"}
    assert {row["principle"] for row in wcag["criteria"]} == {"Perceivable", "Operable", "Understandable", "Robust"}
    assert acr_contract["templateBasis"]["name"] == "VPAT 2.5Rev WCAG Edition"
    assert acr_contract["conformanceLevels"] == ["Supports", "Partially Supports", "Does Not Support", "Not Applicable"]
    assert acr_contract["publicationReadiness"]["automaticCertificationProhibited"] is True

    for specialist in specialists["specialists"]:
        avatar = ROOT / specialist["avatar"]
        assert avatar.is_file() and avatar.suffix == ".jpg"
        assert avatar.stat().st_size < 60_000
        assert jpeg_components(avatar) == 1, f"avatar is not grayscale: {avatar}"

    for skill_name in DOMAIN_SKILLS:
        skill = ROOT / "skills" / skill_name / "SKILL.md"
        agent = ROOT / "skills" / skill_name / "agents" / "openai.yaml"
        source = skill.read_text(encoding="utf-8")
        assert agent.is_file()
        assert "carbon_get_testing_domains" in source
        assert "carbon_publish_command_report" in source
        assert source.count("../../runtime/carbon/references/command-result-reporting.md") == 1
        assert "Open the CARBON report" in source

    with tempfile.TemporaryDirectory(prefix="carbon-specialist-report-") as temporary:
        root = Path(temporary)
        privacy = render(root, {
            "command": "carbon-privacy",
            "title": "Sign-in privacy",
            "summary": "Privacy review completed with remaining runtime gaps.",
            "status": "partial",
            "scope": "sign in",
            "testingDomains": ["privacy"],
            "findings": [{"severity": "high", "title": "Email in request URL", "detail": "Personal data was placed in a query string.", "evidence": "E3 network log"}],
            "confidenceMeter": {"basis": "One observed failure; retention was not assessed.", "missingItems": [{"item": "Retention evidence", "why": "Stored-data lifecycle is unknown."}]},
        })
        privacy_html = Path(privacy["reportPath"]).read_text(encoding="utf-8")
        assert "Pete" in privacy_html
        for name in ("Zanele", "Rajesh", "Sundar"):
            assert name not in privacy_html
        assert privacy_html.count("data:image/jpeg;base64,") == 1
        assert privacy_html.count('class="specialist-ai-badge"') == 1
        assert privacy_html.count('aria-label="AI testing agent"') == 1
        assert privacy_html.count("filter:grayscale(1)!important") == 1
        assert "an AI testing agent" in privacy_html
        assert "Testing perspectives" in privacy_html and "Privacy" in privacy_html

        privacy_unstarted = render(root, {
            "command": "carbon-privacy",
            "title": "Privacy review",
            "summary": "A target was not supplied.",
            "status": "blocked",
            "scope": "current workspace",
            "testingDomains": ["privacy"],
            "evidenceBoundary": "No inspectable target or evidence channel was available.",
        })
        privacy_unstarted_html = Path(privacy_unstarted["reportPath"]).read_text(encoding="utf-8")
        assert "Assessment readiness" in privacy_unstarted_html
        assert "Not a completed Privacy assessment" in privacy_unstarted_html
        assert "Privacy evidence not collected" in privacy_unstarted_html
        assert "What CARBON will examine once a target is available" in privacy_unstarted_html

        accessibility = render(root, {
            "command": "carbon-accessibility",
            "title": "Sign-in accessibility",
            "summary": "Keyboard checks ran; screen-reader behavior remains open.",
            "status": "partial",
            "scope": "sign in",
            "testingDomains": ["accessibility"],
            "wcagResults": {
                "targetLevel": "AA",
                "scope": "Default and validation-error states",
                "pages": ["/signin", "/signin?state=error"],
                "criteria": [
                    {"id": "2.1.1", "outcome": "pass", "method": "keyboard traversal", "evidence": "Every visible control was reached and activated."},
                    {"id": "1.4.3", "outcome": "fail", "method": "computed contrast", "evidence": "Help text was below the target ratio.", "fix": "Increase text contrast."},
                    {"id": "4.1.2", "outcome": "needs-manual-review", "method": "accessibility tree", "evidence": "Names and roles were present; announcement behavior was not observed."},
                ],
            },
            "confidenceMeter": {"basis": "Partial accessibility evidence.", "missingItems": [{"item": "Screen-reader check", "why": "Announcements were not observed."}]},
        })
        assert Path(accessibility["reportPath"]).is_file()
        wcag_report = Path(accessibility["wcagReportPath"])
        acr_report = Path(accessibility["acrReportPath"])
        assert wcag_report.is_file()
        assert acr_report.is_file()
        main_html = Path(accessibility["reportPath"]).read_text(encoding="utf-8")
        wcag_html = wcag_report.read_text(encoding="utf-8")
        acr_html = acr_report.read_text(encoding="utf-8")
        assert str(wcag_report) in main_html
        assert str(acr_report) in main_html
        resolved_root = Path(accessibility["reportPath"]).parents[3]
        assert accessibility["wcagReportLink"].endswith(f"({wcag_report.relative_to(resolved_root).as_posix()})")
        assert accessibility["wcagClaudeFileLink"] == f"[Open the WCAG 2.2 report]({wcag_report})"
        assert accessibility["wcagAbsoluteReportLink"].endswith(f"({wcag_report})")
        assert accessibility["acrReportLink"].endswith(f"({acr_report.relative_to(resolved_root).as_posix()})")
        assert accessibility["acrClaudeFileLink"] == f"[Open the Accessibility Conformance Report]({acr_report})"
        assert accessibility["acrAbsoluteReportLink"].endswith(f"({acr_report})")
        assert accessibility["acrReadiness"] == "Working draft"
        assert accessibility["acrReviewReady"] is False and accessibility["acrPublicationReady"] is False
        assert accessibility["acrUnresolvedCriteria"] == 54
        assert "Alejandro" in main_html and "Hiroshi" not in main_html
        assert wcag_html.count('class="criterion outcome-') == 55
        for value in ("WCAG 2.2", "1.4.3", "Contrast (Minimum)", "fail", "2.1.1", "pass", "needs manual review", "Conformance boundary"):
            assert value in wcag_html
        assert wcag_html.count("data:image/jpeg;base64,") == 1
        assert wcag_html.count('class="specialist-ai-badge"') == 1
        assert wcag_html.count('aria-label="AI testing agent"') == 1
        assert wcag_html.count("filter:grayscale(1)!important") == 1
        assert "<script" not in wcag_html and "<link rel=\"stylesheet\"" not in wcag_html
        assert acr_html.count("<tr class=\"acr-") == 55
        for value in ("Accessibility Conformance Report", "VPAT 2.5Rev WCAG Edition", "Partially Supports", "Not Determined", "Publication-readiness gaps", "not a certification"):
            assert value in acr_html
        assert acr_html.count("data:image/jpeg;base64,") == 1
        assert acr_html.count('class="specialist-ai-badge"') == 1
        assert acr_html.count('aria-label="AI testing agent"') == 1
        assert acr_html.count("filter:grayscale(1)!important") == 1
        assert "<script" not in acr_html and "<link rel=\"stylesheet\"" not in acr_html

        review_ready = render(root, {
            "command": "carbon-accessibility",
            "title": "Acme portal accessibility",
            "summary": "Complete product-scope evidence prepared for owner review.",
            "status": "completed",
            "scope": "Acme portal complete pages and authentication process",
            "testingDomains": ["accessibility"],
            "wcagResults": {
                "targetLevel": "AA",
                "scope": "All applicable Acme portal pages, states, and complete authentication process",
                "pages": ["/", "/signin", "/dashboard"],
                "criteria": [
                    {"id": row["id"], "outcome": "pass", "method": "manual and automated evaluation", "evidence": f'{row["id"]} satisfied in the stated scope.'}
                    for row in wcag["criteria"]
                ],
            },
            "acrMetadata": {
                "productName": "Acme Portal",
                "productVersion": "2.0",
                "productDescription": "Web portal for account access.",
                "contact": "accessibility@example.invalid",
                "reportAuthor": "Acme Accessibility Team",
                "evaluationMethods": ["Keyboard testing", "Screen-reader testing", "Automated rules", "Code inspection"],
                "assistiveTechnologies": ["Representative desktop screen reader"],
                "scopeComplete": True,
                "productOwnerReviewed": False,
            },
        })
        assert review_ready["acrReadiness"] == "Review-ready draft"
        assert review_ready["acrReviewReady"] is True
        assert review_ready["acrPublicationReady"] is False
        review_html = Path(review_ready["acrReportPath"]).read_text(encoding="utf-8")
        assert review_html.count('class="acr-level acr-supports">Supports') == 55
        assert "Product-owner review and approval" in review_html

        broad = render(root, {
            "command": "carbon",
            "title": "First Look — example marketing site",
            "summary": "Broad product review without criterion-level accessibility observations.",
            "status": "completed",
            "scope": "public landing page",
            "testingDomains": ["accessibility", "ui", "privacy"],
        })
        broad_html = Path(broad["reportPath"]).read_text(encoding="utf-8")
        assert "Yuki" in broad_html
        assert broad_html.count("data:image/jpeg;base64,") == 1
        assert "wcagReportPath" not in broad and "acrReportPath" not in broad

    print("PASS: specialist commands, single-channel grayscale assets, enforced grayscale rendering, visible AI identity badges, criterion-level WCAG 2.2 reporting, and conservative VPAT 2.5Rev-aligned ACR generation verified.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
