import os
import sys

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

import backlog_manager


COURSE_ID = "99991"


def _use_tmp_plugin_root(monkeypatch, tmp_path):
    monkeypatch.setattr(backlog_manager, "get_plugin_root", lambda: str(tmp_path))
    course_dir = tmp_path / "courses" / COURSE_ID
    course_dir.mkdir(parents=True, exist_ok=True)
    return course_dir / "course-memory.md"


def _finding(finding_id="finding-1", **overrides):
    finding = {
        "finding_id": finding_id,
        "severity": "critical",
        "finding_text": "Image missing alt text",
        "fix": "Tell Claude: add descriptive alt text",
        "content_type": "page",
        "object_id": "m1-lesson",
        "object_ref": "page: m1-lesson",
    }
    finding.update(overrides)
    return finding


def test_append_finding_writes_valid_pending_entry(monkeypatch, tmp_path):
    memory_path = _use_tmp_plugin_root(monkeypatch, tmp_path)
    memory_path.write_text(
        "## Pending\n\n### Can do now\n\n### Blocked — need instructor input\n",
        encoding="utf-8",
    )

    result = backlog_manager.append_finding(COURSE_ID, _finding())

    assert result["appended"] is True
    text = memory_path.read_text(encoding="utf-8")
    assert "- [CRITICAL] [finding-1] Image missing alt text | fix: Tell Claude: add descriptive alt text" in text
    assert "### Can do now" in text


def test_append_finding_same_id_is_idempotent(monkeypatch, tmp_path):
    memory_path = _use_tmp_plugin_root(monkeypatch, tmp_path)

    first = backlog_manager.append_finding(COURSE_ID, _finding())
    second = backlog_manager.append_finding(COURSE_ID, _finding())

    assert first["appended"] is True
    assert second["appended"] is False
    assert memory_path.read_text(encoding="utf-8").count("[finding-1]") == 1


def test_close_finding_removes_entry_from_pending(monkeypatch, tmp_path):
    memory_path = _use_tmp_plugin_root(monkeypatch, tmp_path)
    backlog_manager.append_finding(COURSE_ID, _finding())

    result = backlog_manager.close_finding(COURSE_ID, "finding-1")

    assert result["removed"] is True
    assert "[finding-1]" not in memory_path.read_text(encoding="utf-8")


def test_cleanup_resolved_removes_resolved_items_only(monkeypatch, tmp_path):
    _use_tmp_plugin_root(monkeypatch, tmp_path)
    backlog_manager.append_finding(COURSE_ID, _finding("resolved"))
    backlog_manager.append_finding(COURSE_ID, _finding("still-present", object_id="m2-lesson"))

    def fake_detector(finding, **_kwargs):
        return finding["finding_id"] != "resolved"

    result = backlog_manager.cleanup_resolved(COURSE_ID, detection_check=fake_detector)
    remaining = {item["finding_id"] for item in backlog_manager.list_findings(COURSE_ID)}

    assert result["removed"] == ["resolved"]
    assert remaining == {"still-present"}


def test_list_findings_filters_by_status(monkeypatch, tmp_path):
    _use_tmp_plugin_root(monkeypatch, tmp_path)
    backlog_manager.append_finding(COURSE_ID, _finding("now"))
    backlog_manager.append_finding(
        COURSE_ID,
        _finding("blocked", status="blocked", blocked=True),
    )

    blocked = backlog_manager.list_findings(COURSE_ID, status="blocked")
    can_do_now = backlog_manager.list_findings(COURSE_ID, status="can_do_now")

    assert [item["finding_id"] for item in blocked] == ["blocked"]
    assert [item["finding_id"] for item in can_do_now] == ["now"]


def test_append_finding_creates_pending_section_when_missing(monkeypatch, tmp_path):
    memory_path = _use_tmp_plugin_root(monkeypatch, tmp_path)
    memory_path.write_text("## Current State\n\nNo backlog section yet.\n", encoding="utf-8")

    backlog_manager.append_finding(COURSE_ID, _finding())

    text = memory_path.read_text(encoding="utf-8")
    assert "## Pending" in text
    assert "### Can do now" in text
    assert "### Blocked — need instructor input" in text
    assert "[finding-1]" in text
