import pytest

from app.repositories import snapshot_graph_repo
from tests.integration.fakes import FakeIntegrationDB, seed_chunked_snapshot_graph, seed_snapshot_graph


def test_is_chunked_manifest_explicit_flag():
    assert snapshot_graph_repo.is_chunked_manifest({"chunked": True, "nodes": []}) is True


def test_is_chunked_manifest_infers_from_part_count():
    assert snapshot_graph_repo.is_chunked_manifest({"part_count": 2, "nodes": [], "edges": []}) is True


def test_is_chunked_manifest_inline_graph_not_chunked():
    assert snapshot_graph_repo.is_chunked_manifest({"part_count": 0, "nodes": [{"id": "n1"}]}) is False


def test_reassemble_graph_payload_concatenates_parts():
    nodes, edges = snapshot_graph_repo.reassemble_graph_payload(
        [
            {"part_index": 1, "nodes": [], "edges": [{"id": "e1"}]},
            {"part_index": 0, "nodes": [{"id": "n1"}], "edges": []},
        ]
    )
    assert [node["id"] for node in nodes] == ["n1"]
    assert [edge["id"] for edge in edges] == ["e1"]


@pytest.mark.asyncio
async def test_get_merged_inline_graph(monkeypatch):
    fake_db = FakeIntegrationDB()
    seed_snapshot_graph(fake_db)
    monkeypatch.setattr(snapshot_graph_repo, "get_code_chunks_db", lambda: fake_db)

    graph = await snapshot_graph_repo.get_merged("AD/example-repo", "snap_abc123")

    assert graph is not None
    assert graph.chunked is False
    assert len(graph.nodes) == 2
    assert len(graph.edges) == 1


@pytest.mark.asyncio
async def test_get_merged_chunked_graph(monkeypatch):
    fake_db = FakeIntegrationDB()
    seed_chunked_snapshot_graph(fake_db)
    monkeypatch.setattr(snapshot_graph_repo, "get_code_chunks_db", lambda: fake_db)

    graph = await snapshot_graph_repo.get_merged("AD/example-repo", "snap_abc123")

    assert graph is not None
    assert graph.chunked is True
    assert graph.part_count == 2
    assert len(graph.nodes) == 2
    assert len(graph.edges) == 1


@pytest.mark.asyncio
async def test_get_merged_returns_none_for_repo_mismatch(monkeypatch):
    fake_db = FakeIntegrationDB()
    seed_snapshot_graph(fake_db, repo_id="AD/other-repo")
    monkeypatch.setattr(snapshot_graph_repo, "get_code_chunks_db", lambda: fake_db)

    graph = await snapshot_graph_repo.get_merged("AD/example-repo", "snap_abc123")

    assert graph is None
