"""Fireflies.ai Transcript plugin — TranscriptProvider + SummaryProvider.

GraphQL API integration for meeting transcripts, summaries, action items,
and attendees. Requires FIREFLIES_API_KEY in .env.

API docs: https://docs.fireflies.ai/getting-started/quickstart
Endpoint: https://api.fireflies.ai/graphql
Auth: Bearer token
"""

from __future__ import annotations

import logging
import os
from typing import Any

logger = logging.getLogger(__name__)

FIREFLIES_API_URL = "https://api.fireflies.ai/graphql"


class FirefliesClient:
    """Low-level GraphQL client for the Fireflies API."""

    def __init__(self, api_key: str | None = None) -> None:
        self.api_key = api_key or os.getenv("FIREFLIES_API_KEY", "")
        if not self.api_key:
            logger.warning("FIREFLIES_API_KEY not set — Fireflies integration unavailable")

    def _headers(self) -> dict[str, str]:
        return {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}",
        }

    def _query(self, query: str, variables: dict | None = None) -> dict:
        """Execute a GraphQL query. Returns the response data dict."""
        import requests

        payload: dict[str, Any] = {"query": query}
        if variables:
            payload["variables"] = variables
        resp = requests.post(
            FIREFLIES_API_URL,
            headers=self._headers(),
            json=payload,
            timeout=30,
        )
        resp.raise_for_status()
        result = resp.json()
        if "errors" in result:
            logger.error("Fireflies API errors: %s", result["errors"])
        return result.get("data", {})

    def list_transcripts(self, limit: int = 10) -> list[dict]:
        """List recent transcripts."""
        query = f"""
        query {{
            transcripts(limit: {limit}) {{
                id
                title
                date
                duration
                organizer_email
                participants
                transcript_url
            }}
        }}
        """
        data = self._query(query)
        return data.get("transcripts", [])

    def get_transcript(self, transcript_id: str) -> dict:
        """Get a full transcript with sentences and summary."""
        query = """
        query GetTranscript($id: String!) {
            transcript(id: $id) {
                id
                title
                date
                duration
                organizer_email
                participants
                sentences {
                    speaker_name
                    text
                    start_time
                    end_time
                }
                summary {
                    action_items
                    outline
                    shorthand_bullet
                    overview
                    keywords
                }
            }
        }
        """
        data = self._query(query, {"id": transcript_id})
        return data.get("transcript", {})


class FirefliesTranscriptAdapter:
    """Implements TranscriptProvider protocol for Fireflies.ai."""

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

    async def fetch_transcript(self, recording_id: str) -> dict[str, Any]:
        """Fetch a transcript by ID. Returns {text, speakers, metadata}."""
        data = self._client.get_transcript(recording_id)
        if not data:
            return {"text": "", "speakers": [], "metadata": {}}

        # Build full text from sentences
        sentences = data.get("sentences", [])
        text_parts = []
        speakers = set()
        for s in sentences:
            speaker = s.get("speaker_name", "Unknown")
            speakers.add(speaker)
            text_parts.append(f"{speaker}: {s.get('text', '')}")

        return {
            "text": "\n".join(text_parts),
            "speakers": sorted(speakers),
            "metadata": {
                "title": data.get("title", ""),
                "date": data.get("date", ""),
                "duration": data.get("duration", 0),
                "organizer": data.get("organizer_email", ""),
                "participants": data.get("participants", []),
                "source": "fireflies",
            },
        }

    async def list_recordings(
        self,
        start_date: str | None = None,
        end_date: str | None = None,
    ) -> list[dict[str, Any]]:
        """List available transcripts."""
        transcripts = self._client.list_transcripts(limit=20)
        results = []
        for t in transcripts:
            results.append(
                {
                    "recording_id": t.get("id", ""),
                    "title": t.get("title", ""),
                    "date": t.get("date", ""),
                    "duration": t.get("duration", 0),
                    "participants": t.get("participants", []),
                    "source": "fireflies",
                }
            )
        return results


class FirefliesSummaryAdapter:
    """Implements SummaryProvider protocol for Fireflies.ai summaries."""

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

    async def summarize(self, recording_id: str) -> dict[str, Any]:
        """Get Fireflies' own AI summary for a transcript."""
        data = self._client.get_transcript(recording_id)
        if not data:
            return {"summary": "", "action_items": [], "keywords": []}

        summary = data.get("summary", {})
        return {
            "summary": summary.get("overview", "") or summary.get("shorthand_bullet", ""),
            "action_items": summary.get("action_items", []),
            "outline": summary.get("outline", ""),
            "keywords": summary.get("keywords", []),
            "source": "fireflies",
        }


def register() -> None:
    """Register Fireflies plugins with the loader."""
    from vastian.loader import loader_register

    loader_register("fireflies_transcript", FirefliesTranscriptAdapter)
    loader_register("fireflies_summary", FirefliesSummaryAdapter)
