from __future__ import annotations

from uuid import UUID

from src.domain.livechat.repository import LivechatRepository
from src.domain.livechat.schemas import LivechatConfigResponse, UpdateLivechatConfigRequest, LivechatTranscriptPurgeResponse
from src.integrations.cloud_control_client import CloudControlClient


class LivechatService:
    def __init__(self, *, repo: LivechatRepository, cloud_client: CloudControlClient) -> None:
        self._repo = repo
        self._cloud = cloud_client

    async def get_or_create_config(self, project_id: UUID, workspace_id: UUID) -> LivechatConfigResponse:
        row = await self._repo.get_config(project_id) or await self._repo.upsert_config(project_id)
        await self._push(workspace_id, row)
        return LivechatConfigResponse.model_validate(row)

    async def update_config(self, project_id: UUID, workspace_id: UUID, body: UpdateLivechatConfigRequest) -> LivechatConfigResponse:
        row = await self._repo.upsert_config(project_id, **body.model_dump(exclude_unset=True))
        await self._push(workspace_id, row)
        return LivechatConfigResponse.model_validate(row)

    async def purge_transcripts(self, project_id: UUID) -> LivechatTranscriptPurgeResponse:
        result = await self._cloud.purge_livechat_transcripts(str(project_id))
        return LivechatTranscriptPurgeResponse(
            ok=bool(result.get("ok", True)),
            deleted=int(result.get("deleted") or 0),
            remaining=int(result.get("remaining") or 0),
        )

    async def _push(self, workspace_id: UUID, row) -> None:
        await self._cloud.push_livechat_config(
            project_id=str(row.project_id), workspace_id=str(workspace_id), enabled=row.enabled,
            provider=row.provider, billing_mode=row.billing_mode, credential_ref=row.credential_ref,
            model=row.model, instructions=row.instructions, max_tokens=row.max_tokens,
            transcript_retention_days=row.transcript_retention_days, retain_audio=row.retain_audio,
            agent_id=row.agent_id, agent_version_id=row.agent_version_id,
            tools=row.tools_json or [],
        )
