import json
import os
import sys

sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts"))

import audit_report
import backlog_manager


def _patch_roots(monkeypatch, tmp_path):
    monkeypatch.setattr(audit_report, "PLUGIN_ROOT", tmp_path)
    monkeypatch.setattr(audit_report, "REPORTS_DIR", tmp_path / "reports")
    monkeypatch.setattr(backlog_manager, "get_plugin_root", lambda: str(tmp_path))
    if audit_report.backlog_manager is not None:
        monkeypatch.setattr(audit_report.backlog_manager, "get_plugin_root", lambda: str(tmp_path))


def _base_report_data(items):
    return {
        "course": {
            "name": "Backlog Test Course",
            "id": "99992",
            "institution": "Arizona State University",
        },
        "audit_date": "2026-05-18T12:00:00",
        "sections": {
            "design_standards": {
                "title": "Design",
                "subtitle": "",
                "summary": {"Met": 0, "Partially Met": 0, "Not Met": 0},
                "items": [],
            },
            "qa_categories": {
                "title": "QA",
                "subtitle": "",
                "summary": {"Pass": 0, "Warn": 0, "Fail": len(items)},
                "items": items,
            },
            "accessibility": {
                "title": "Accessibility",
                "subtitle": "",
                "summary": {"Critical": 0, "Warning": 0, "Info": 0},
                "items": [],
            },
            "readiness": {
                "title": "Readiness",
                "subtitle": "",
                "overall": "READY",
                "categories": [],
            },
        },
    }


def test_running_audit_report_produces_backlog_entries(monkeypatch, tmp_path):
    _patch_roots(monkeypatch, tmp_path)
    data = audit_report.generate_demo_data()
    input_path = tmp_path / "audit.json"
    input_path.write_text(json.dumps(data), encoding="utf-8")
    monkeypatch.setattr(
        sys,
        "argv",
        ["audit_report.py", "--input", str(input_path), "--course-id", "99992"],
    )

    audit_report.main()

    findings = backlog_manager.list_findings("99992")
    assert findings
    assert any(item["finding_id"].startswith("audit-report") for item in findings)


def test_top_n_filter_limits_qa_section_to_10_items():
    items = [
        {"id": f"Q{i:02d}", "name": f"QA Top {i:02d}", "status": "Fail", "detail": "Needs work"}
        for i in range(12)
    ]
    html = audit_report.generate_report(_base_report_data(items))
    qa_section = html.split('id="section-qa"', 1)[1].split('id="section-a11y"', 1)[0]

    assert qa_section.count("QA Top") == 10
    assert "QA Top 09" in qa_section
    assert "QA Top 10" not in qa_section
    assert "QA Top 11" not in qa_section


def test_fix_path_annotations_present_on_findings():
    html = audit_report.generate_report(audit_report.generate_demo_data())

    assert "Fix path:" in html
    assert "Tell Claude:" in html


def test_object_reference_annotations_present_on_findings():
    html = audit_report.generate_report(audit_report.generate_demo_data())

    assert "Object:" in html
    assert "https://canvas.asu.edu/courses/218764/pages/" in html
