"""TranscriptAdapter — routes raw transcripts to agents, optionally via VastianSummaryAdapter.

LEGACY: This adapter is registered but not called from the runtime.
The canonical pipeline is: inbox -> Charles triage -> Maya extract_signals tool.
Pocket/Fireflies provide their own summaries (skip re-summarization).
Only raw Teams paste/manual input would need this adapter's summarization.
"""

from __future__ import annotations

import json
import logging
from datetime import UTC, datetime
from pathlib import Path

logger = logging.getLogger(__name__)

_VastianSummaryAdapter = None
try:
    from vastian.plugins.vastian_summary import VastianSummaryAdapter

    _VastianSummaryAdapter = VastianSummaryAdapter
except ImportError:
    pass


def _get_state_dir() -> Path:
    """Return state/content-bridge/transcript directory (uses data root when set)."""
    from vastian.storage.data_root import get_data_root

    root = get_data_root(None)
    return root / "state" / "content-bridge" / "transcript"


class TranscriptAdapter:
    """ContentBridge adapter for raw transcripts.

    If metadata.auto_summarize is True (default), attempts to generate
    a summary via VastianSummaryAdapter before routing. Falls back to
    raw transcript if summary fails or is disabled.
    """

    def get_target_agents(self, content: str, metadata: dict) -> list[str]:
        """Same as MeetingSummaryAdapter — charles, liam, arjuna, maya.

        Adds finley if metadata has "financial" signal.
        """
        explicit = metadata.get("target_agents")
        if isinstance(explicit, list) and explicit:
            agents = list(explicit)
        elif isinstance(explicit, str) and explicit:
            agents = [explicit.strip()]
        else:
            agents = ["charles", "liam", "arjuna", "maya"]

        if metadata.get("financial") and "finley" not in agents:
            agents = agents + ["finley"]

        return agents

    # Sources that already provide summaries — skip re-summarization
    PRE_SUMMARIZED_SOURCES = {"pocket_api", "fireflies_api"}

    async def ingest(self, content: str, metadata: dict) -> dict:
        """Process transcript: optionally summarize first, then route.

        If source is Pocket or Fireflies, skip summarization (they provide
        their own summaries). Only raw transcripts (Teams paste, manual CLI)
        need VastianSummaryAdapter summarization.
        """
        summary: str | None = metadata.get("summary")  # Pre-existing summary from source
        source = metadata.get("source", "")
        auto_summarize = metadata.get("auto_summarize", True)

        # Skip summarization for sources that already provide summaries
        if source in self.PRE_SUMMARIZED_SOURCES:
            auto_summarize = False
            logger.debug("Source %s provides own summary, skipping re-summarization", source)

        if auto_summarize and summary is None and _VastianSummaryAdapter is not None:
            try:
                adapter = _VastianSummaryAdapter()
                result = await adapter.generate_summary(content, metadata.get("template"))
                if isinstance(result, dict):
                    s = result.get("summary")
                    if s is not None:
                        summary = s if isinstance(s, str) else str(s)
            except Exception as e:
                logger.warning("VastianSummaryAdapter failed, using raw transcript: %s", e)
                summary = None

        agents = self.get_target_agents(content, metadata)
        out: dict = {
            "routed_to": agents,
            "raw_length": len(content),
            "status": "ingested",
        }
        if summary is not None:
            out["summary"] = summary
        logger.info("Transcript ingested, routing to %s (summary=%s)", agents, summary is not None)
        return out

    def persist_outcomes(self, results: dict) -> None:
        """Write outcomes to state/content-bridge/transcript/ as JSON."""
        out_dir = _get_state_dir()
        out_dir.mkdir(parents=True, exist_ok=True)
        timestamp = datetime.now(UTC).strftime("%Y%m%d_%H%M%S")
        filename = f"{timestamp}_transcript.json"
        path = out_dir / filename
        try:
            path.write_text(json.dumps(results, indent=2, default=str), encoding="utf-8")
            logger.info("Persisted transcript outcomes to %s", path)
        except OSError as e:
            logger.error("Failed to persist transcript outcomes: %s", e)


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

    loader_register("transcript_bridge", TranscriptAdapter)
