"""Pocket summary plugin — uses Pocket's AI-generated summaries."""

from __future__ import annotations

import os


class PocketSummaryAdapter:
    """SummaryProvider adapter wrapping Pocket's own AI summary."""

    def __init__(self, api_key: str | None = None) -> None:
        """Initialize with API key or read from POCKET_API_KEY env."""
        self.api_key = api_key or os.environ.get("POCKET_API_KEY", "")
        self._client: object | None = None

    def _get_client(self) -> object:
        """Lazy-load PocketClient. Raises NotImplementedError if unavailable."""
        if self._client is not None:
            return self._client
        try:
            from vastian.plugins.pocket_transcript.client import PocketClient

            self._client = PocketClient(api_key=self.api_key)
            return self._client
        except ImportError:
            raise NotImplementedError(
                "PocketSummaryAdapter requires PocketClient from "
                "plugins/pocket_transcript/client.py (Wave 2C)"
            ) from None

    async def generate_summary(self, transcript: str, template: str | None = None) -> dict:
        """Generate summary from transcript or recording_id.

        If transcript is a recording_id, fetch from Pocket and extract
        latest summary. Otherwise use transcript text (Pocket may not
        support this directly — treat as recording_id for now).
        """
        client = self._get_client()
        # Treat transcript as recording_id; fetch from Pocket
        recording = client.get_recording(transcript, include_summary=True)
        if isinstance(recording, dict):
            summary_text = recording.get("summary", "") or recording.get("ai_summary", "")
            metadata = recording.get("metadata", recording)
        else:
            summary_text = (
                getattr(recording, "summary", None) or getattr(recording, "ai_summary", "") or ""
            )
            metadata = getattr(recording, "metadata", {}) or {}

        action_items: list[dict] = []
        if hasattr(client, "extract_action_items"):
            result = client.extract_action_items(summary_text)
            action_items = result if isinstance(result, list) else []

        return {
            "summary": str(summary_text or ""),
            "signals": {},
            "action_items": action_items,
            "metadata": {
                "provider": "pocket_ai",
                **(metadata if isinstance(metadata, dict) else {}),
            },
        }

    async def extract_action_items(self, text: str) -> list[dict]:
        """Extract action items using PocketClient or simple parsing."""
        try:
            client = self._get_client()
            if hasattr(client, "extract_action_items"):
                return client.extract_action_items(text)
        except NotImplementedError:
            pass
        # Fallback: parse basic patterns like "- [ ] task" or "* action"
        items: list[dict] = []
        for line in text.splitlines():
            line = line.strip()
            if line.startswith(("-", "*", "•")) or line.lower().startswith("action"):
                items.append({"text": line, "raw": line})
        return items


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

    loader_register("pocket_summary", PocketSummaryAdapter)
