"""Time management utilities for meeting phases."""

import time
from enum import Enum
from typing import Dict, Any, Tuple


class TimeUrgency(Enum):
    """Time urgency levels for meeting phase management."""
    NORMAL = "normal"              # < 50% elapsed
    SOFT_WARNING = "soft_warning"  # 50-79% elapsed
    URGENT_WARNING = "urgent"      # 80-99% elapsed
    HARD_CUTOFF = "cutoff"        # >= 100% elapsed


def get_phase_time_info(state: Dict[str, Any]) -> Tuple[float, float, float, TimeUrgency]:
    """Calculate time information for current phase.

    Args:
        state: Meeting state dictionary

    Returns:
        Tuple of (elapsed_seconds, remaining_seconds, percentage, urgency_level)
    """
    current_phase = state.get("current_phase", "opening")
    phase_start = state.get("phase_start_time", time.time())
    phase_limits = state.get("phase_time_limits", {})

    # Get time limit for current phase (default to 300 seconds if not set)
    time_limit = phase_limits.get(current_phase, 300)

    # Calculate elapsed time
    elapsed = time.time() - phase_start
    remaining = max(0, time_limit - elapsed)
    percentage = (elapsed / time_limit) * 100 if time_limit > 0 else 0

    # Determine urgency level
    if percentage >= 100:
        urgency = TimeUrgency.HARD_CUTOFF
    elif percentage >= 80:
        urgency = TimeUrgency.URGENT_WARNING
    elif percentage >= 50:
        urgency = TimeUrgency.SOFT_WARNING
    else:
        urgency = TimeUrgency.NORMAL

    return elapsed, remaining, percentage, urgency


def build_time_context_for_host(state: Dict[str, Any]) -> str:
    """Build time context string for host agent prompt injection.

    Args:
        state: Meeting state dictionary

    Returns:
        Time context string to inject into host prompt (empty if NORMAL)
    """
    elapsed, remaining, percentage, urgency = get_phase_time_info(state)
    current_phase = state.get("current_phase", "opening")
    time_extended = state.get("time_extended", False)

    if urgency == TimeUrgency.NORMAL:
        return ""

    elif urgency == TimeUrgency.SOFT_WARNING:
        return f"""
**TIME AWARENESS ({percentage:.0f}% elapsed):**
- Current phase: {current_phase}
- Time elapsed: {int(elapsed)}초 / Remaining: {int(remaining)}초
- Consider starting to guide the discussion toward conclusion naturally.
- Use phrases like: "시간이 얼마 남지 않았으니 핵심 내용을 정리해주시면 좋겠습니다"
"""

    elif urgency == TimeUrgency.URGENT_WARNING:
        extension_note = ""
        if not time_extended:
            extension_note = """
- **ACTION REQUIRED:** Ask the human participant if they want to extend time:
  - Say: "시간이 부족한데, 이 안건 논의를 연장할까요? 아니면 마무리하고 넘어갈까요?"
  - Listen for extension keywords: "연장", "더", "계속", "extend"
"""
        else:
            extension_note = """
- Time extension was already used for this phase.
- Push firmly for conclusion - no more extensions available.
"""

        return f"""
⚠️ **TIME CRITICAL ({percentage:.0f}% elapsed):**
- Current phase: {current_phase}
- Time elapsed: {int(elapsed)}초 / Remaining: {int(remaining)}초
{extension_note}
- If no extension, use firm language: "시간이 부족하니 마무리 발언 부탁드립니다"
- Prioritize wrapping up the current discussion.
"""

    # HARD_CUTOFF is handled in node_select_speaker before LLM call
    return ""


def check_extension_request(text: str) -> bool:
    """Check if user input contains time extension keywords.

    Args:
        text: User input text

    Returns:
        True if extension keywords detected
    """
    extension_keywords = ["연장", "더", "계속", "extend", "more time", "추가"]
    text_lower = text.lower()
    return any(keyword in text_lower for keyword in extension_keywords)


def apply_time_extension(state: Dict[str, Any]) -> Dict[str, int]:
    """Apply 50% time extension to current phase.

    Args:
        state: Meeting state dictionary

    Returns:
        Updated phase_time_limits dictionary
    """
    current_phase = state.get("current_phase", "opening")
    phase_limits = state.get("phase_time_limits", {}).copy()

    # Get current limit
    current_limit = phase_limits.get(current_phase, 300)

    # Add 50% extension
    extended_limit = int(current_limit * 1.5)
    phase_limits[current_phase] = extended_limit

    return phase_limits
