"""MeetingSummaryAdapter — routes processed meeting summaries to agents.

LEGACY: This adapter is registered but not called from the runtime.
The canonical pipeline is: inbox -> Charles triage -> Maya extract_signals tool
-> _route_meeting_signals (orchestrator). This adapter exists for potential
future use as a formal ContentBridge entry point but is not currently wired.
"""

from __future__ import annotations

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

logger = logging.getLogger(__name__)

_MEETING_ANALYZER_AVAILABLE = False
_parse_adaptive = None
_extract_signals_from_sections = None

try:
    from vastian.meeting_analyzer import extract_signals_from_sections, parse_adaptive

    _parse_adaptive = parse_adaptive
    _extract_signals_from_sections = extract_signals_from_sections
    _MEETING_ANALYZER_AVAILABLE = True
except ImportError:
    pass


def _get_state_dir() -> Path:
    """Return state/content-bridge/meeting 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" / "meeting"


class MeetingSummaryAdapter:
    """ContentBridge adapter for processed meeting summaries."""

    def get_target_agents(self, content: str, metadata: dict) -> list[str]:
        """Determine which agents should process meeting summaries.

        Default: charles (briefing/overview), liam (action items for cycle planning),
        arjuna (ticket creation), maya (meeting intelligence).
        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"]
            logger.debug("Added finley due to financial signal")

        return agents

    async def ingest(self, content: str, metadata: dict) -> dict:
        """Process meeting summary and route to target agents.

        Extracts signals from content if not already present.
        Pocket and Fireflies summaries already have structured data —
        signal extraction still runs to normalize the format.
        """
        signals: dict | None = metadata.get("signals")

        if (
            signals is None
            and _MEETING_ANALYZER_AVAILABLE
            and _parse_adaptive is not None
            and _extract_signals_from_sections is not None
        ):
            try:
                sections = _parse_adaptive(content)
                signals = _extract_signals_from_sections(sections)
                logger.debug("Extracted signals from meeting content")
            except Exception as e:
                logger.warning("Could not extract signals from meeting: %s", e)
                signals = None

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

    def persist_outcomes(self, results: dict) -> None:
        """Write outcomes to state/content-bridge/meeting/ 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}_meeting.json"
        path = out_dir / filename
        try:
            path.write_text(json.dumps(results, indent=2, default=str), encoding="utf-8")
            logger.info("Persisted meeting outcomes to %s", path)
        except OSError as e:
            logger.error("Failed to persist meeting outcomes: %s", e)


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

    loader_register("meeting_summary_bridge", MeetingSummaryAdapter)
