from app.models.upstream.doc_chunk import DocChunkDocument
from app.models.upstream.snapshot_graph import SnapshotGraphDocument, SnapshotGraphNode
from app.services.repo_overview_builder import (
    build_overview_text,
    overview_chunk_hash,
    overview_record_id,
)


def test_build_overview_text_prefers_readme_and_architecture():
    chunks = [
        DocChunkDocument(
            chunk_id="chk_misc",
            repo_id="AD/example-repo",
            doc_path="docs/misc.md",
            section_title="Misc",
            chunk_text="Misc details.",
            chunk_hash="h1",
        ),
        DocChunkDocument(
            chunk_id="chk_readme",
            repo_id="AD/example-repo",
            doc_path="README.md",
            section_title="Intro",
            chunk_text="This repo provides code intelligence and RAG.",
            chunk_hash="h2",
        ),
        DocChunkDocument(
            chunk_id="chk_arch",
            repo_id="AD/example-repo",
            doc_path="architecture.md",
            section_title="Overview",
            chunk_text="Four microservices power the indexing pipeline.",
            chunk_hash="h3",
        ),
    ]

    text = build_overview_text(
        repo_id="AD/example-repo",
        doc_chunks=chunks,
    )

    assert text is not None
    assert "Repository overview: AD/example-repo" in text
    assert "README.md" in text
    assert "architecture.md" in text
    assert text.index("README.md") < text.index("docs/misc.md")


def test_build_overview_text_includes_graph_summary():
    graph = SnapshotGraphDocument(
        repo_id="AD/example-repo",
        snapshot_id="snap_abc123",
        nodes=[
            SnapshotGraphNode(id="f1", kind="file", name="main.go", path="cmd/server/main.go"),
            SnapshotGraphNode(id="f2", kind="file", name="app.go", path="internal/app/app.go"),
        ],
    )

    text = build_overview_text(
        repo_id="AD/example-repo",
        doc_chunks=[],
        graph=graph,
    )

    assert text is not None
    assert "Repository structure:" in text
    assert "cmd/server/main.go" in text


def test_build_overview_text_returns_none_without_content():
    assert build_overview_text(repo_id="AD/empty", doc_chunks=[], graph=None) is None


def test_overview_record_id_is_stable():
    first = overview_record_id("AD/example-repo", "snap_abc123")
    second = overview_record_id("AD/example-repo", "snap_abc123")
    assert first == second
    assert first.startswith("emb_overview_")


def test_overview_chunk_hash_changes_with_text():
    assert overview_chunk_hash("alpha") != overview_chunk_hash("beta")
