import uuid

from qdrant_client.http import models as qm

from app.repositories.mysql_repository import MySQLRepository
from app.repositories.qdrant_repository import QdrantRepository
from app.services.embedding_service import EmbeddingService
from app.utils.chunking import semantic_chunk_by_speaker_turns


class IngestionService:
    def __init__(self, qdrant_repo: QdrantRepository, mysql_repo: MySQLRepository, emb_service: EmbeddingService):
        self.qdrant = qdrant_repo
        self.mysql = mysql_repo
        self.emb = emb_service

    def ingest_call(self, tenant_id: str, call_id: str, agent_id: str, timestamp, tags: list[str], transcript: list[dict]) -> int:
        chunks = semantic_chunk_by_speaker_turns(call_id=call_id, turns=transcript)
        if not chunks:
            self.mysql.save_call_ingestion(tenant_id, call_id, agent_id, 0, tags)
            return 0

        vectors = self.emb.embed_texts([c.text for c in chunks])
        self.qdrant.ensure_collection(vector_size=len(vectors[0]))

        points: list[qm.PointStruct] = []
        for chunk, vec in zip(chunks, vectors):
            payload = {
                'tenant_id': tenant_id,
                'call_id': call_id,
                'agent_id': agent_id,
                'timestamp': (chunk.timestamp or timestamp).isoformat() if (chunk.timestamp or timestamp) else None,
                'speaker': chunk.speaker,
                'text': chunk.text,
                'tags': tags,
                'chunk_id': chunk.chunk_id,
                'chunk_index': chunk.idx,
            }
            points.append(
                qm.PointStruct(
                    id=str(uuid.uuid4()),
                    vector=vec,
                    payload=payload,
                )
            )

            self.mysql.save_chunk_metadata(
                tenant_id=tenant_id,
                call_id=call_id,
                agent_id=agent_id,
                chunk_index=chunk.idx,
                chunk_id=chunk.chunk_id,
                speaker=chunk.speaker,
                text=chunk.text,
                timestamp=chunk.timestamp or timestamp,
            )

        self.qdrant.upsert_chunks(points)
        self.mysql.save_call_ingestion(tenant_id, call_id, agent_id, len(chunks), tags)
        return len(chunks)
