import os
import sys
import types

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

import backlog_manager


COURSE_ID = "99994"


def _use_tmp_plugin_root(monkeypatch, tmp_path):
    monkeypatch.setattr(backlog_manager, "get_plugin_root", lambda: str(tmp_path))
    (tmp_path / "courses" / COURSE_ID).mkdir(parents=True, exist_ok=True)


def _mock_canvas_surfaces(monkeypatch):
    monkeypatch.setitem(sys.modules, "staging_manager", types.SimpleNamespace())
    monkeypatch.setitem(sys.modules, "push_to_canvas", types.SimpleNamespace())


def test_empty_rubric_backlog_entry_has_rubric_creator_fix_path(monkeypatch, tmp_path):
    _use_tmp_plugin_root(monkeypatch, tmp_path)
    _mock_canvas_surfaces(monkeypatch)

    record = backlog_manager.add(COURSE_ID, {
        "finding_type": "empty_rubric",
        "detail": "Rubric has no populated criteria.",
        "rubric_name": "Evidence Analysis Rubric",
        "assignment_name": "Module 3 Artifact",
    })

    assert "rubric-creator" in record["fix_path"]
    assert "Evidence Analysis Rubric" in record["fix_path"]


def test_mlo_rewrite_backlog_entry_has_update_module_fix_path(monkeypatch, tmp_path):
    _use_tmp_plugin_root(monkeypatch, tmp_path)
    _mock_canvas_surfaces(monkeypatch)

    record = backlog_manager.add(COURSE_ID, {
        "finding_type": "mlo_rewrite",
        "detail": "Module objective drift detected.",
        "module": "Module 4",
        "mlo_text": "Analyze statutory interpretation exceptions.",
    })

    assert "update-module" in record["fix_path"]
    assert "Module 4" in record["fix_path"]


def test_title_alignment_backlog_entry_has_page_edit_fix_path(monkeypatch, tmp_path):
    _use_tmp_plugin_root(monkeypatch, tmp_path)
    _mock_canvas_surfaces(monkeypatch)

    record = backlog_manager.add(COURSE_ID, {
        "finding_type": "title_alignment",
        "detail": "Page title no longer matches the module naming pattern.",
        "page_title": "Module 2 Overview",
        "page_id": "m2-overview",
    })

    assert "page-edit" in record["fix_path"]
    assert "Module 2 Overview" in record["fix_path"]
