import asyncio

import pytest

from app.models.embedding_record import EmbeddingRecord
from app.models.enums import ChunkType, SourceType
from app.models.upstream.doc_chunk import DocChunkDocument
from app.services import embedding_record_builder


def test_from_repo_overview_maps_summary_docs_record():
    record = EmbeddingRecord.from_repo_overview(
        record_id="emb_overview_test",
        repo_id="AD/example-repo",
        snapshot_id="snap_abc123",
        commit_sha="abc123",
        text="Repository overview content.",
        chunk_hash="sha256:overview",
    )

    assert record.source_type == SourceType.DOCS
    assert record.chunk_type == ChunkType.SUMMARY
    assert record.doc_path == "REPO_OVERVIEW.md"
    assert record.section_title == "Repository Overview"


def test_build_snapshot_records_adds_overview_record(monkeypatch):
    doc_chunk = DocChunkDocument(
        chunk_id="chk_readme",
        repo_id="AD/example-repo",
        doc_path="README.md",
        section_title="Intro",
        chunk_text="A code intelligence platform.",
        chunk_hash="sha256:readme",
        metadata={"snapshot_id": "snap_abc123", "commit_hash": "abc123"},
    )

    async def _list_docs(_repo_id, _snapshot_id):
        return [doc_chunk]

    async def _list_code(_repo_id, _snapshot_id):
        return []

    async def _existing(*_args, **_kwargs):
        return {}

    async def _graph(_repo_id, _snapshot_id):
        return None

    monkeypatch.setattr(embedding_record_builder.doc_chunk_repo, "list_by_snapshot", _list_docs)
    monkeypatch.setattr(embedding_record_builder.code_chunk_repo, "list_by_snapshot", _list_code)
    monkeypatch.setattr(embedding_record_builder, "_load_existing_records", _existing)
    monkeypatch.setattr(embedding_record_builder.snapshot_graph_repo, "get_merged", _graph)

    result = asyncio.run(
        embedding_record_builder.build_snapshot_records(
            "AD/example-repo",
            "snap_abc123",
            "abc123",
        )
    )

    assert result.built_count == 2
    overview_items = [
        item for item in result.items if item.record.chunk_type == ChunkType.SUMMARY
    ]
    assert len(overview_items) == 1
    assert overview_items[0].record.doc_path == "REPO_OVERVIEW.md"
