"""Agenda management for meetings."""

import time
from dataclasses import dataclass, field
from enum import Enum
from typing import Optional


class AgendaStatus(Enum):
    """Status of an agenda item."""

    PENDING = "pending"
    IN_PROGRESS = "in_progress"
    DECIDED = "decided"
    DEFERRED = "deferred"


@dataclass
class AgendaItem:
    """Represents an agenda item."""

    title: str
    time_limit: int = 300  # seconds (5 minutes default)
    owner: Optional[str] = None
    status: AgendaStatus = AgendaStatus.PENDING
    decision: Optional[str] = None
    action_items: list[str] = field(default_factory=list)
    start_time: Optional[float] = None
    end_time: Optional[float] = None

    def start(self) -> None:
        """Start this agenda item."""
        self.status = AgendaStatus.IN_PROGRESS
        self.start_time = time.time()

    def complete(self, decision: Optional[str] = None) -> None:
        """Complete this agenda item.

        Args:
            decision: Decision made (if any)
        """
        self.status = AgendaStatus.DECIDED
        self.end_time = time.time()
        if decision:
            self.decision = decision

    def defer(self) -> None:
        """Defer this agenda item."""
        self.status = AgendaStatus.DEFERRED
        self.end_time = time.time()

    def add_action_item(self, action: str) -> None:
        """Add an action item.

        Args:
            action: Action item description
        """
        self.action_items.append(action)

    def elapsed_time(self) -> float:
        """Get elapsed time in seconds.

        Returns:
            Elapsed time or 0 if not started
        """
        if self.start_time is None:
            return 0.0
        end = self.end_time or time.time()
        return end - self.start_time

    def is_over_time(self) -> bool:
        """Check if this item is over time.

        Returns:
            True if elapsed time exceeds limit
        """
        return self.elapsed_time() > self.time_limit


@dataclass
class Decision:
    """Represents a decision made in the meeting."""

    description: str
    rationale: Optional[str] = None
    timestamp: float = field(default_factory=time.time)


@dataclass
class ActionItem:
    """Represents an action item from the meeting."""

    description: str
    assignee: Optional[str] = None
    deadline: Optional[str] = None
    timestamp: float = field(default_factory=time.time)


class AgendaManager:
    """Manages agenda items and extracts decisions/actions."""

    def __init__(self):
        """Initialize agenda manager."""
        self._agenda_items: list[AgendaItem] = []
        self._current_item: Optional[AgendaItem] = None
        self._decisions: list[Decision] = []
        self._action_items: list[ActionItem] = []

    @property
    def current_item(self) -> Optional[AgendaItem]:
        """Get current agenda item."""
        return self._current_item

    @property
    def agenda_items(self) -> list[AgendaItem]:
        """Get all agenda items."""
        return self._agenda_items.copy()

    @property
    def decisions(self) -> list[Decision]:
        """Get all decisions."""
        return self._decisions.copy()

    @property
    def action_items(self) -> list[ActionItem]:
        """Get all action items."""
        return self._action_items.copy()

    def add_agenda_item(
        self,
        title: str,
        time_limit: int = 300,
        owner: Optional[str] = None,
    ) -> AgendaItem:
        """Add an agenda item.

        Args:
            title: Agenda item title
            time_limit: Time limit in seconds
            owner: Owner of this item

        Returns:
            Created agenda item
        """
        item = AgendaItem(title=title, time_limit=time_limit, owner=owner)
        self._agenda_items.append(item)
        return item

    def start_item(self, item: AgendaItem) -> None:
        """Start an agenda item.

        Args:
            item: Item to start
        """
        if self._current_item is not None:
            self._current_item.complete()

        self._current_item = item
        item.start()

    def complete_current_item(self, decision: Optional[str] = None) -> None:
        """Complete the current agenda item.

        Args:
            decision: Decision made
        """
        if self._current_item is not None:
            self._current_item.complete(decision)
            if decision:
                self.add_decision(decision)
            self._current_item = None

    def defer_current_item(self) -> None:
        """Defer the current agenda item."""
        if self._current_item is not None:
            self._current_item.defer()
            self._current_item = None

    def add_decision(self, description: str, rationale: Optional[str] = None) -> None:
        """Add a decision.

        Args:
            description: Decision description
            rationale: Decision rationale
        """
        decision = Decision(description=description, rationale=rationale)
        self._decisions.append(decision)

        # Also add to current item if exists
        if self._current_item is not None:
            self._current_item.decision = description

    def add_action_item(
        self,
        description: str,
        assignee: Optional[str] = None,
        deadline: Optional[str] = None,
    ) -> None:
        """Add an action item.

        Args:
            description: Action description
            assignee: Person assigned
            deadline: Deadline string
        """
        action = ActionItem(
            description=description,
            assignee=assignee,
            deadline=deadline,
        )
        self._action_items.append(action)

        # Also add to current item if exists
        if self._current_item is not None:
            self._current_item.add_action_item(description)

    def get_summary(self) -> dict:
        """Get meeting summary.

        Returns:
            Summary dictionary
        """
        return {
            "total_items": len(self._agenda_items),
            "completed_items": len(
                [i for i in self._agenda_items if i.status == AgendaStatus.DECIDED]
            ),
            "deferred_items": len(
                [i for i in self._agenda_items if i.status == AgendaStatus.DEFERRED]
            ),
            "decisions": [
                {"description": d.description, "rationale": d.rationale}
                for d in self._decisions
            ],
            "action_items": [
                {
                    "description": a.description,
                    "assignee": a.assignee,
                    "deadline": a.deadline,
                }
                for a in self._action_items
            ],
        }

    def format_summary(self) -> str:
        """Format summary as readable text.

        Returns:
            Formatted summary
        """
        lines = ["Meeting Summary", "=" * 60, ""]

        # Decisions
        lines.append(f"Decisions Made: {len(self._decisions)}")
        for i, decision in enumerate(self._decisions, 1):
            lines.append(f"{i}. {decision.description}")
            if decision.rationale:
                lines.append(f"   Rationale: {decision.rationale}")
        lines.append("")

        # Action Items
        lines.append(f"Action Items: {len(self._action_items)}")
        for i, action in enumerate(self._action_items, 1):
            assignee = f" (@{action.assignee})" if action.assignee else ""
            deadline = f" [Due: {action.deadline}]" if action.deadline else ""
            lines.append(f"{i}. {action.description}{assignee}{deadline}")
        lines.append("")

        # Deferred Items
        deferred = [i for i in self._agenda_items if i.status == AgendaStatus.DEFERRED]
        if deferred:
            lines.append(f"Deferred Items: {len(deferred)}")
            for item in deferred:
                lines.append(f"- {item.title}")
            lines.append("")

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