import json

import pytest

from app.models.events import EmbeddingJobDispatchEvent
from app.services.embedding_dispatch_service import to_embedding_task_request


def _event(payload: dict) -> EmbeddingJobDispatchEvent:
    return EmbeddingJobDispatchEvent(
        event_type="embedding.job.created",
        event_version="1",
        created_at="2026-06-04T12:00:00Z",
        job_id="emb_1",
        repo_id="ad/repo",
        snapshot_id="snap_1",
        document_id="doc_1",
        chunk_id="chk_1",
        status="pending",
        payload=json.dumps(payload),
    )


def test_to_embedding_task_request_maps_event_payload():
    event = _event(
        {
            "chunk_id": "chk_1",
            "repo_id": "ad/repo",
            "snapshot_id": "snap_1",
            "document_id": "doc_1",
            "chunk_text": "Some docs text",
            "source_type": "repo_doc",
            "chunk_type": "text",
            "doc_path": "docs/api.md",
            "section_title": "API",
            "section_level": 1,
            "chunk_hash": "hash_1",
            "metadata": {"heading_path": "Docs / API"},
        }
    )

    result = to_embedding_task_request(event)

    assert result["job_id"] == "emb_1"
    assert result["chunk_id"] == "chk_1"
    assert result["chunk_text"] == "Some docs text"
    assert result["metadata"]["heading_path"] == "Docs / API"
    assert result["metadata"]["repo_id"] == "ad/repo"


def test_to_embedding_task_request_rejects_invalid_payload():
    event = _event({"chunk_id": "chk_1"})

    with pytest.raises(ValueError, match="does not match chunk contract"):
        to_embedding_task_request(event)
