"""Agenda extraction and formatting utilities for meeting management."""

import json
from typing import List, Optional
from langchain_core.language_models import BaseChatModel
from langchain_core.messages import BaseMessage, SystemMessage, HumanMessage
from pydantic import BaseModel, Field
from tabulate import tabulate

from .state import AgendaItemInfo


class AgendaExtractionResult(BaseModel):
    """Result of agenda extraction from conversation."""
    items: List[AgendaItemInfo] = Field(
        default_factory=list,
        description="Updated list of all agenda items"
    )
    changes_summary: Optional[str] = Field(
        default=None,
        description="Summary of changes made (for debugging)"
    )


def extract_agenda_updates(
    llm: BaseChatModel,
    messages: List[BaseMessage],
    current_items: List[AgendaItemInfo],
    current_phase: str,
) -> AgendaExtractionResult:
    """
    Extract and update agenda items from recent conversation.

    Args:
        llm: Language model to use for extraction
        messages: Recent conversation messages (last 10-15 turns)
        current_items: Current list of agenda items
        current_phase: Current meeting phase

    Returns:
        AgendaExtractionResult with updated agenda items
    """
    # Prepare current agenda context
    current_agenda_text = ""
    if current_items:
        current_agenda_text = "**Current Agenda Items:**\n"
        for idx, item in enumerate(current_items, 1):
            status_emoji = {
                "pending": "⏳",
                "in_progress": "🔄",
                "decided": "✅",
                "deferred": "⏸️"
            }.get(item.status, "❓")
            owner_text = f" (담당: {item.owner})" if item.owner else ""
            decision_text = f" → \"{item.decision}\"" if item.decision else ""
            current_agenda_text += f"{idx}. {status_emoji} {item.title}{owner_text}{decision_text}\n"
    else:
        current_agenda_text = "**Current Agenda Items:** (없음)\n"

    # Prepare conversation context
    conversation_text = ""
    for msg in messages[-10:]:  # Last 10 messages
        role = "Host" if msg.name == "Host" else msg.name
        conversation_text += f"**{role}**: {msg.content}\n\n"

    # Create extraction prompt
    system_prompt = f"""당신은 회의 안건을 추출하고 관리하는 AI입니다.

**현재 회의 단계:** {current_phase}

{current_agenda_text}

**최근 대화 내용:**
{conversation_text}

**안건 추출 규칙:**
1. 구체적인 논의 주제만 안건으로 등록 (일반 인사, 잡담은 제외)
2. 상태 변경은 대화에 명확한 근거가 있을 때만
3. 기존 안건은 절대 삭제하지 않음 (업데이트만 가능)
4. 제목은 한국어로 작성, 30자 이내
5. 담당자(owner)는 명시적으로 언급된 경우만 설정
6. 결정사항(decision)은 명확한 결론이 나왔을 때만 기록

**상태 종류:**
- pending: 아직 논의 안 됨
- in_progress: 현재 논의 중
- decided: 결정 완료
- deferred: 보류/연기

대화 내용을 분석하여 안건 목록을 업데이트하세요. 변경사항이 없으면 기존 목록을 그대로 반환하세요."""

    try:
        # Try structured output first
        structured_llm = llm.with_structured_output(AgendaExtractionResult)
        result = structured_llm.invoke([
            SystemMessage(content=system_prompt),
            HumanMessage(content="위 대화를 분석하여 안건 목록을 업데이트해주세요.")
        ])
        return result

    except Exception as e:
        # Fallback: try JSON parsing
        try:
            response = llm.invoke([
                SystemMessage(content=system_prompt + "\n\nJSON 형식으로 응답하세요."),
                HumanMessage(content="위 대화를 분석하여 안건 목록을 업데이트해주세요.")
            ])

            # Extract JSON from response
            content = response.content
            if "```json" in content:
                content = content.split("```json")[1].split("```")[0]
            elif "```" in content:
                content = content.split("```")[1].split("```")[0]

            data = json.loads(content.strip())

            # Convert to AgendaExtractionResult
            items = [AgendaItemInfo(**item) for item in data.get("items", [])]
            return AgendaExtractionResult(
                items=items,
                changes_summary=data.get("changes_summary")
            )

        except Exception as inner_e:
            # Final fallback: return current items unchanged
            print(f"⚠️ 안건 추출 실패 (유지): {e}, {inner_e}")
            return AgendaExtractionResult(
                items=current_items,
                changes_summary=f"추출 실패, 기존 안건 유지: {str(e)}"
            )


def format_agenda_status_bar(items: List[AgendaItemInfo]) -> str:
    """
    Format agenda items as a list display.

    Args:
        items: List of agenda items

    Returns:
        Formatted string, empty if no items
    """
    if not items:
        return ""

    lines = ["\n📋 현재 안건 목록:"]
    
    for item in items:
        status_emoji = {
            "pending": "⏳",
            "in_progress": "🔄",
            "decided": "✅",
            "deferred": "⏸️"
        }.get(item.status, "❓")

        # Format: {상태} {안건}({담당자})
        # Apply rich styling based on status
        title_text = item.title
        if item.status == "in_progress":
            title_text = f"[green]{title_text}[/green]"
        elif item.status == "decided":
            title_text = f"[gray strike]{title_text}[/gray strike]"

        # If owner is present, include it in parentheses
        owner_str = f"({item.owner})" if item.owner else ""
        header_line = f"  {status_emoji} {title_text}{owner_str}"
        lines.append(header_line)
        
        # Format:  └─ {결정사항}
        # Only show decision line if there is a decision
        if item.decision:
            decision_line = f"     └─ {item.decision}"
            lines.append(decision_line)

    return "\n".join(lines)


def format_agenda_phase_summary(
    items: List[AgendaItemInfo],
    from_phase: str,
    to_phase: str
) -> str:
    """
    Format agenda items as a detailed summary table for phase transitions.

    Args:
        items: List of agenda items
        from_phase: Previous phase name
        to_phase: New phase name

    Returns:
        Formatted summary table
    """
    if not items:
        return ""

    separator = "━" * 60
    header = f"📋 안건 진행 현황 ({from_phase} → {to_phase})"

    lines = [separator, header]

    for item in items:
        status_emoji = {
            "pending": "⏳",
            "in_progress": "🔄",
            "decided": "✅",
            "deferred": "⏸️"
        }.get(item.status, "❓")

        # Apply rich styling based on status
        title_text = item.title
        if item.status == "in_progress":
            title_text = f"[green]{title_text}[/green]"
        elif item.status == "decided":
            title_text = f"[gray strike]{title_text}[/gray strike]"

        # Build status line
        parts = [
            f"  {status_emoji} {title_text}",
            f"│ {item.status}"
        ]

        if item.owner:
            parts.append(f"│ {item.owner}")

        if item.decision:
            # Truncate long decisions
            decision = item.decision if len(item.decision) <= 40 else item.decision[:37] + "..."
            parts.append(f"│ \"{decision}\"")

        lines.append(" ".join(parts))

    lines.append(separator)

    return "\n".join(lines)
