import os
import sys
from unittest.mock import Mock

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


def test_criterion_evaluator_emits_audit_completed(monkeypatch, capsys):
    import criterion_evaluator

    timeline = Mock()
    timeline.append_event.return_value = {"ok": True}
    results = [
        {
            "criterion_id": "B-22.1",
            "status": "Not Met",
            "needs_ai_review": False,
        },
        {
            "criterion_id": "B-04.1",
            "status": "Partially Met",
            "needs_ai_review": False,
        },
    ]

    monkeypatch.setattr(criterion_evaluator, "timeline_logger", timeline)
    monkeypatch.setattr(criterion_evaluator, "collect_course_data", lambda *args, **kwargs: {
        "course_id": "12345",
        "course_name": "Test Course",
        "domain": "canvas.test.edu",
        "pages": [],
        "imgs_total": 0,
    })
    monkeypatch.setattr(criterion_evaluator, "evaluate_all", lambda *args, **kwargs: results)
    monkeypatch.setattr(sys, "argv", [
        "criterion_evaluator.py",
        "--json",
        "--skip-link-validation",
    ])

    criterion_evaluator.main()
    capsys.readouterr()

    timeline.append_event.assert_called_once()
    course_id, event_type, payload = timeline.append_event.call_args.args
    assert course_id == "12345"
    assert event_type == "audit_completed"
    assert payload["audit_type"] == "course_audit"
    assert payload["finding_count"] == 2
    assert payload["severity_distribution"] == {
        "critical": 1,
        "warning": 1,
        "info": 0,
    }


def test_push_verified_event_includes_content_type_and_object_id(monkeypatch):
    import push_to_canvas

    emitted = []

    class Timeline:
        def emit_event(self, course_id, event_type, payload):
            emitted.append((course_id, event_type, payload))

    monkeypatch.setattr(push_to_canvas, "timeline_logger", Timeline())
    monkeypatch.setattr(push_to_canvas.staging_manager, "get_staged", lambda *args: "<p>New</p>")
    monkeypatch.setattr(push_to_canvas.canvas_api, "get_page", lambda *args: {"body": "<p>Old</p>"})
    monkeypatch.setattr(push_to_canvas.backup_manager, "save_backup", lambda *args, **kwargs: None)
    monkeypatch.setattr(push_to_canvas.canvas_api, "update_page", lambda *args, **kwargs: True)
    monkeypatch.setattr(push_to_canvas.post_write_verify, "verify_page", lambda *args: {
        "ok": True,
        "canvas_url": "https://canvas.test.edu/courses/12345/pages/m1-overview",
        "warnings": [],
        "content_length": 10,
    })
    monkeypatch.setattr(push_to_canvas.staging_manager, "clear_staged", lambda *args: None)
    monkeypatch.setattr(push_to_canvas, "_track_progress", lambda *args, **kwargs: None)

    result = push_to_canvas.push_page(
        {"domain": "canvas.test.edu", "course_id": "12345"},
        "m1-overview",
        "12345",
    )

    assert result["ok"] is True
    verified = [event for event in emitted if event[1] == "push_verified"]
    assert len(verified) == 1
    payload = verified[0][2]
    assert payload["object_id"] == "m1-overview"
    assert payload["content_type"] == "page"
