"""Synthesis utilities for Mentor Council meetings."""

from __future__ import annotations

from vastian.council.session import Contribution, CouncilSession


def extract_themes(contributions: list[Contribution]) -> dict[str, list[str]]:
    """
    Extract common themes from council contributions.

    Returns a dict of theme -> list of agent_ids who mentioned it.
    This is a simple keyword-based extraction; LLM-based extraction
    is handled by the synthesizer agent.
    """
    # Common theme keywords to look for
    theme_keywords = {
        "alignment": ["align", "alignment", "sync", "coherent", "consistent"],
        "priority": ["priority", "prioritize", "urgent", "critical", "important"],
        "integration": ["integrate", "integration", "connect", "unified", "cross-module"],
        "risk": ["risk", "concern", "worry", "challenge", "obstacle"],
        "opportunity": ["opportunity", "potential", "growth", "expand", "improve"],
        "timeline": ["timeline", "deadline", "schedule", "milestone", "date"],
        "resource": ["resource", "budget", "capacity", "bandwidth", "staffing"],
    }

    themes: dict[str, list[str]] = {}

    for contribution in contributions:
        content_lower = contribution.content.lower()
        for theme, keywords in theme_keywords.items():
            if any(kw in content_lower for kw in keywords):
                if theme not in themes:
                    themes[theme] = []
                if contribution.agent_id not in themes[theme]:
                    themes[theme].append(contribution.agent_id)

    return themes


def calculate_consensus_score(session: CouncilSession) -> float:
    """
    Calculate a rough consensus score (0.0 to 1.0) based on:
    - How many agents had dissent notes
    - How much contributions converged over rounds
    """
    if not session.contributions:
        return 0.0

    total_members = len(session.member_ids)
    if total_members == 0:
        return 0.0

    # Count members who expressed dissent
    dissenters = set()
    for c in session.contributions:
        if c.dissent_from:
            dissenters.add(c.agent_id)

    dissent_ratio = len(dissenters) / total_members
    consensus = 1.0 - dissent_ratio

    return max(0.0, min(1.0, consensus))


def format_council_report(session: CouncilSession) -> str:
    """Format a complete council report suitable for user presentation."""
    themes = extract_themes(session.contributions)
    consensus = calculate_consensus_score(session)

    lines = [
        "=" * 60,
        "  MENTOR COUNCIL REPORT",
        f"  Type: {session.council_type.value.replace('_', ' ').title()}",
        "=" * 60,
        "",
        f"Topic: {session.topic}",
        f"Members: {', '.join(session.member_ids)}",
        f"Rounds: {session.current_round}",
        f"Consensus Score: {consensus:.0%}",
        "",
    ]

    if themes:
        lines.append("Key Themes Discussed:")
        for theme, agents in themes.items():
            lines.append(f"  - {theme.title()}: raised by {', '.join(agents)}")
        lines.append("")

    if session.synthesis:
        lines.append("-" * 40)
        lines.append("SYNTHESIS")
        lines.append("-" * 40)
        lines.append(session.synthesis)
        lines.append("")

    if session.action_items:
        lines.append("-" * 40)
        lines.append("ACTION ITEMS")
        lines.append("-" * 40)
        for i, item in enumerate(session.action_items, 1):
            lines.append(f"  {i}. [{item.priority.upper()}] {item.description}")
            lines.append(f"     Assigned to: {item.assigned_to}")
        lines.append("")

    lines.append("=" * 60)
    return "\n".join(lines)
