"""Pocket Transcript plugin — API-based transcript retrieval via PocketClient.

Provides PocketTranscriptAdapter implementing TranscriptProvider protocol,
plus the raw PocketClient for direct API access.
"""

from __future__ import annotations

import logging
from typing import Any

from .client import PocketClient

logger = logging.getLogger(__name__)

__all__ = ["PocketClient", "PocketTranscriptAdapter"]


class PocketTranscriptAdapter:
    """TranscriptProvider for Pocket API-based transcript retrieval.

    Wraps PocketClient to satisfy the TranscriptProvider protocol.
    Requires POCKET_API_KEY env var or explicit api_key.
    """

    def __init__(self, api_key: str | None = None) -> None:
        self._client: PocketClient | None = None
        self._api_key = api_key

    def _get_client(self) -> PocketClient:
        """Lazy-init client (avoids import-time API key requirement)."""
        if self._client is None:
            self._client = PocketClient(api_key=self._api_key)
        return self._client

    async def fetch_transcript(self, recording_id: str) -> dict:
        """Fetch a transcript by Pocket recording ID.

        Returns {text, speakers, metadata} matching TranscriptProvider contract.
        """
        client = self._get_client()
        try:
            data = client.get_recording(
                recording_id,
                include_transcript=True,
                include_summarizations=False,
            )
        except Exception as e:
            logger.error("Pocket API error fetching recording %s: %s", recording_id, e)
            return {"text": "", "speakers": [], "metadata": {"error": str(e)}}

        # Extract transcript text from API response
        recording: dict[str, Any] = data.get("recording", data)
        transcript_entries = recording.get("transcript", [])

        if isinstance(transcript_entries, list):
            # Pocket returns transcript as list of {speaker, text, start, end}
            lines: list[str] = []
            speakers_seen: set[str] = set()
            speakers_ordered: list[str] = []
            for entry in transcript_entries:
                if isinstance(entry, dict):
                    speaker = entry.get("speaker", "Unknown")
                    text = entry.get("text", "")
                    lines.append(f"{speaker}: {text}")
                    if speaker not in speakers_seen:
                        speakers_seen.add(speaker)
                        speakers_ordered.append(speaker)
            transcript_text = "\n".join(lines)
            speakers = speakers_ordered
        elif isinstance(transcript_entries, str):
            transcript_text = transcript_entries
            speakers = []
        else:
            transcript_text = ""
            speakers = []

        return {
            "text": transcript_text,
            "speakers": speakers,
            "metadata": {
                "source": "pocket_api",
                "recording_id": recording_id,
                "title": recording.get("title", ""),
                "duration": recording.get("duration"),
                "created_at": recording.get("created_at"),
            },
        }

    async def list_recordings(
        self,
        start_date: str | None = None,
        end_date: str | None = None,
    ) -> list[dict]:
        """List available Pocket recordings, optionally filtered by date."""
        client = self._get_client()
        try:
            data = client.list_recordings(
                start_date=start_date,
                end_date=end_date,
            )
        except Exception as e:
            logger.error("Pocket API error listing recordings: %s", e)
            return []

        recordings = data.get("recordings", [])
        if not isinstance(recordings, list):
            recordings = []

        return [
            {
                "id": r.get("id", ""),
                "title": r.get("title", "Untitled"),
                "created_at": r.get("created_at"),
                "duration": r.get("duration"),
                "source": "pocket_api",
            }
            for r in recordings
            if isinstance(r, dict)
        ]


def register() -> None:
    """Register the Pocket transcript adapter with the loader."""
    from vastian.loader import register as loader_register

    loader_register("pocket_transcript", PocketTranscriptAdapter)
