from __future__ import annotations

from typing import Any

from app.models.embedding_record import EmbeddingRecord


def embedding_record_to_qdrant_payload(record: EmbeddingRecord) -> dict[str, Any]:
    """Map an embedding record to the Qdrant payload schema (TW-87)."""
    payload: dict[str, Any] = {
        "record_id": record.record_id,
        "repo_id": record.repo_id,
        "snapshot_id": record.snapshot_id,
        "source_type": record.source_type.value,
        "chunk_type": record.chunk_type.value,
    }

    if record.commit_sha:
        payload["commit_sha"] = record.commit_sha
    if record.start_line is not None:
        payload["start_line"] = record.start_line
    if record.end_line is not None:
        payload["end_line"] = record.end_line
    if record.file_path:
        payload["file_path"] = record.file_path
    if record.doc_path:
        payload["doc_path"] = record.doc_path
    if record.graph_node_id:
        payload["graph_node_id"] = record.graph_node_id
    if record.symbol_name:
        payload["symbol_name"] = record.symbol_name
    if record.section_title:
        payload["section_title"] = record.section_title
    if record.artifact_uri:
        payload["artifact_uri"] = record.artifact_uri

    metadata = record.metadata
    if hasattr(metadata, "model_dump"):
        extra = metadata.model_dump(exclude_none=True)
    elif isinstance(metadata, dict):
        extra = {k: v for k, v in metadata.items() if v is not None}
    else:
        extra = {}

    for key, value in extra.items():
        payload.setdefault(key, value)

    return payload
