"""Council session — represents a single Mentor Council meeting."""

from __future__ import annotations

import uuid
from datetime import UTC, datetime
from enum import StrEnum

from pydantic import BaseModel, Field


class CouncilType(StrEnum):
    STRATEGIC_REVIEW = "strategic_review"
    OPERATIONAL_SYNC = "operational_sync"
    SCENARIO_WORKSHOP = "scenario_workshop"
    FULL_COUNCIL = "full_council"
    AD_HOC = "ad_hoc"


class CouncilPhase(StrEnum):
    CONVENE = "convene"
    DELIBERATE = "deliberate"
    SYNTHESIZE = "synthesize"
    DELIVER = "deliver"
    COMPLETED = "completed"


class Contribution(BaseModel):
    """A single agent's contribution during deliberation."""

    agent_id: str
    agent_name: str
    round_number: int
    content: str
    timestamp: datetime = Field(default_factory=lambda: datetime.now(UTC))
    references: list[str] = Field(default_factory=list)  # document references
    dissent_from: list[str] = Field(default_factory=list)  # agent_ids disagreed with


class ActionItem(BaseModel):
    """An action item generated from the council meeting."""

    id: str = Field(default_factory=lambda: uuid.uuid4().hex[:8])
    description: str
    assigned_to: str  # agent_id
    priority: str = "normal"
    due_context: str = ""  # "by next sync", "this week", etc.
    status: str = "pending"


class CouncilSession(BaseModel):
    """
    A single Mentor Council meeting session.

    Tracks the full lifecycle: convene -> deliberate -> synthesize -> deliver.
    """

    id: str = Field(default_factory=lambda: uuid.uuid4().hex[:12])
    council_type: CouncilType
    topic: str
    context: str = ""  # briefing context
    phase: CouncilPhase = CouncilPhase.CONVENE
    member_ids: list[str] = Field(default_factory=list)
    contributions: list[Contribution] = Field(default_factory=list)
    current_round: int = 0
    max_rounds: int = 5
    synthesis: str = ""
    dissent_notes: list[str] = Field(default_factory=list)
    action_items: list[ActionItem] = Field(default_factory=list)
    synthesizer_id: str = ""  # agent responsible for synthesis
    created_at: datetime = Field(default_factory=lambda: datetime.now(UTC))
    completed_at: datetime | None = None

    def add_contribution(
        self,
        agent_id: str,
        agent_name: str,
        content: str,
        references: list[str] | None = None,
        dissent_from: list[str] | None = None,
    ) -> Contribution:
        """Record an agent's contribution."""
        contribution = Contribution(
            agent_id=agent_id,
            agent_name=agent_name,
            round_number=self.current_round,
            content=content,
            references=references or [],
            dissent_from=dissent_from or [],
        )
        self.contributions.append(contribution)
        return contribution

    def get_round_contributions(self, round_number: int) -> list[Contribution]:
        """Get all contributions from a specific round."""
        return [c for c in self.contributions if c.round_number == round_number]

    def get_agent_contributions(self, agent_id: str) -> list[Contribution]:
        """Get all contributions from a specific agent."""
        return [c for c in self.contributions if c.agent_id == agent_id]

    def advance_round(self) -> bool:
        """Advance to next round. Returns False if max rounds reached."""
        if self.current_round >= self.max_rounds:
            return False
        self.current_round += 1
        return True

    @property
    def transcript(self) -> str:
        """Generate a readable transcript of the meeting."""
        lines = [
            f"# Mentor Council Meeting — {self.council_type.value.replace('_', ' ').title()}",
            f"**Topic:** {self.topic}",
            f"**Members:** {', '.join(self.member_ids)}",
            f"**Date:** {self.created_at.strftime('%Y-%m-%d %H:%M UTC')}",
            "",
        ]

        current_round = -1
        for contrib in self.contributions:
            if contrib.round_number != current_round:
                current_round = contrib.round_number
                lines.append(f"\n## Round {current_round}")
                lines.append("")

            lines.append(f"### {contrib.agent_name}")
            lines.append(contrib.content)
            if contrib.dissent_from:
                lines.append(f"*Dissent from: {', '.join(contrib.dissent_from)}*")
            lines.append("")

        if self.synthesis:
            lines.append("\n## Synthesis")
            lines.append(self.synthesis)

        if self.action_items:
            lines.append("\n## Action Items")
            for item in self.action_items:
                lines.append(f"- [{item.priority.upper()}] {item.description} → {item.assigned_to}")

        return "\n".join(lines)

    def to_summary(self) -> dict:
        """Generate a summary dict for API responses."""
        return {
            "id": self.id,
            "type": self.council_type.value,
            "topic": self.topic,
            "phase": self.phase.value,
            "members": self.member_ids,
            "rounds_completed": self.current_round,
            "total_contributions": len(self.contributions),
            "synthesis": self.synthesis[:500] if self.synthesis else "",
            "action_items": [item.model_dump(mode="json") for item in self.action_items],
            "created_at": self.created_at.isoformat(),
            "completed_at": self.completed_at.isoformat() if self.completed_at else None,
        }
