"""Vastian summary plugin — uses ported meeting analyzer for summaries."""

from __future__ import annotations

_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


class VastianSummaryAdapter:
    """SummaryProvider using the ported meeting analyzer."""

    def __init__(self) -> None:
        """No configuration needed."""

    async def generate_summary(self, transcript: str, template: str | None = None) -> dict:
        """Generate structured summary via meeting analyzer.

        1. Parse with parse_adaptive(transcript)
        2. Extract signals with extract_signals_from_sections(sections)
        3. Return formatted summary with signals and action items.
        """
        if (
            not _MEETING_ANALYZER_AVAILABLE
            or _parse_adaptive is None
            or _extract_signals_from_sections is None
        ):
            raise NotImplementedError(
                "VastianSummaryAdapter requires meeting_analyzer from "
                "vastian.analysis.meeting_analyzer (Wave 2C). "
                "Ensure parse_adaptive and extract_signals_from_sections are available."
            ) from None

        sections = _parse_adaptive(transcript)
        signals = _extract_signals_from_sections(sections)

        action_items = []
        if isinstance(signals, dict) and "action_item" in signals:
            action_items = signals.get("action_item", [])
            if not isinstance(action_items, list):
                action_items = [action_items] if action_items else []

        # Format summary text from sections
        formatted_lines: list[str] = []
        for sec in sections if isinstance(sections, (list, tuple)) else [sections]:
            if hasattr(sec, "content"):
                formatted_lines.append(str(sec.content))
            elif isinstance(sec, dict):
                formatted_lines.append(sec.get("content", str(sec)))
            else:
                formatted_lines.append(str(sec))
        formatted_text = "\n\n".join(formatted_lines)

        return {
            "summary": formatted_text,
            "signals": signals if isinstance(signals, dict) else {},
            "action_items": action_items,
            "metadata": {"provider": "vastian_analyzer"},
        }

    async def extract_action_items(self, text: str) -> list[dict]:
        """Extract action items using meeting analyzer if available."""
        if (
            not _MEETING_ANALYZER_AVAILABLE
            or _parse_adaptive is None
            or _extract_signals_from_sections is None
        ):
            raise NotImplementedError(
                "VastianSummaryAdapter requires meeting_analyzer (Wave 2C)."
            ) from None

        sections = _parse_adaptive(text)
        signals = _extract_signals_from_sections(sections)
        action_items = signals.get("action_item", []) if isinstance(signals, dict) else []
        if not isinstance(action_items, list):
            return [action_items] if action_items else []
        return [item if isinstance(item, dict) else {"text": str(item)} for item in action_items]


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

    loader_register("vastian_summary", VastianSummaryAdapter)
