from grantflow.api.idempotency_store_facade import _set_job
from grantflow.tests.review_traceability_helpers import client


def test_versions_and_diff_endpoints():
    job_id = "test-job-versions-1"
    _set_job(
        job_id,
        {
            "status": "done",
            "hitl_enabled": False,
            "state": {
                "draft_versions": [
                    {
                        "version_id": "toc_v1",
                        "sequence": 1,
                        "section": "toc",
                        "node": "architect",
                        "iteration": 1,
                        "content": {"toc": {"brief": "v1", "project": "Water"}},
                        "content_hash": "hash1",
                    },
                    {
                        "version_id": "toc_v2",
                        "sequence": 2,
                        "section": "toc",
                        "node": "architect",
                        "iteration": 2,
                        "content": {"toc": {"brief": "v2", "project": "Water"}},
                        "content_hash": "hash2",
                    },
                    {
                        "version_id": "logframe_v1",
                        "sequence": 3,
                        "section": "logframe",
                        "node": "mel_specialist",
                        "iteration": 2,
                        "content": {"indicators": [{"indicator_id": "IND_001"}]},
                        "content_hash": "hash3",
                    },
                ]
            },
        },
    )

    versions_resp = client.get(f"/status/{job_id}/versions")
    assert versions_resp.status_code == 200
    versions_body = versions_resp.json()
    assert versions_body["job_id"] == job_id
    assert versions_body["version_count"] == 3
    assert [v["version_id"] for v in versions_body["versions"]] == ["toc_v1", "toc_v2", "logframe_v1"]

    toc_versions_resp = client.get(f"/status/{job_id}/versions", params={"section": "toc"})
    assert toc_versions_resp.status_code == 200
    assert toc_versions_resp.json()["version_count"] == 2

    diff_resp = client.get(f"/status/{job_id}/diff", params={"section": "toc"})
    assert diff_resp.status_code == 200
    diff_body = diff_resp.json()
    assert diff_body["job_id"] == job_id
    assert diff_body["section"] == "toc"
    assert diff_body["from_version_id"] == "toc_v1"
    assert diff_body["to_version_id"] == "toc_v2"
    assert diff_body["has_diff"] is True
    assert "toc_v1" in diff_body["diff_text"]
    assert "toc_v2" in diff_body["diff_text"]
    assert any(line.startswith("-") or line.startswith("+") for line in diff_body["diff_lines"])
