"""
Minutes Manager

Submits STT transcripts to the gateway's minutes store and
downloads completed conference minutes in JSON or TXT format.

REST API:
  POST /api/v1/minutes/{confId}/transcript   — Submit utterance
  GET  /api/v1/minutes/{confId}/download     — Download minutes
"""

from __future__ import annotations

import json
from typing import Awaitable, Callable, Literal
from urllib.parse import quote

from dvgateway.transport.http_client import HttpClient
from dvgateway.types import Logger, TranscriptResult


class MinutesManager:
    """Manages conference minutes and transcript submission."""

    def __init__(self, http: HttpClient, logger: Logger) -> None:
        self._http = http
        self._logger = logger

    async def submit_transcript(self, conf_id: str, result: TranscriptResult) -> None:
        """Submit an STT transcript result to the gateway's minutes store."""
        response = await self._http.post(
            f"/api/v1/minutes/{quote(conf_id)}/transcript",
            body={
                "linkedId": result.linked_id,
                "text": result.text,
                "isFinal": result.is_final,
                "speaker": result.speaker,
                "confidence": result.confidence,
                "timestampMs": result.timestamp_ms,
                "sentiment": result.sentiment.sentiment if result.sentiment else None,
                "sentimentScore": result.sentiment.sentiment_score if result.sentiment else None,
            },
        )
        if response.status not in (200, 201, 204):
            raise RuntimeError(f"Failed to submit transcript: HTTP {response.status}")

    async def download_minutes(
        self,
        conf_id: str,
        format: Literal["json", "txt"] = "txt",
    ) -> str:
        """Download conference minutes in JSON or plain-text format."""
        accept = "application/json" if format == "json" else "text/plain"
        response = await self._http.get(
            f"/api/v1/minutes/{quote(conf_id)}/download",
            headers={"Accept": accept},
        )
        if response.status != 200:
            raise RuntimeError(f"Failed to download minutes: HTTP {response.status}")

        if format == "json" and isinstance(response.data, dict):
            return json.dumps(response.data, indent=2)
        return str(response.data)

    def create_auto_submitter(self, conf_id: str) -> Callable[[TranscriptResult], Awaitable[None]]:
        """Returns a function that auto-submits final transcripts to minutes."""
        async def auto_submit(result: TranscriptResult) -> None:
            if not result.is_final:
                return
            try:
                await self.submit_transcript(conf_id, result)
            except Exception as e:
                self._logger.warn({"conf_id": conf_id, "err": str(e)}, "Failed to auto-submit transcript to minutes")

        return auto_submit
