"""Context management for conversation history"""

import time
from typing import List, Dict, Any, Tuple
from dataclasses import dataclass
from collections import deque


@dataclass
class ConversationTurn:
    """Single conversation turn"""

    timestamp: float
    user_input: str
    ai_response: str


class ContextManager:
    """Manages conversation context and memory"""

    def __init__(self, max_turns: int = 2):
        self.max_turns = max_turns
        self.turns: deque[ConversationTurn] = deque(maxlen=max_turns)

    def add_turn(self, user_input: str, ai_response: str) -> None:
        """Add a new conversation turn"""
        turn = ConversationTurn(
            timestamp=time.time(),
            user_input=user_input.strip(),
            ai_response=ai_response.strip(),
        )
        self.turns.append(turn)

    def get_context_for_model(self, model: str) -> str:
        """Get formatted context string for the model"""
        if not self.turns:
            return ""

        # Adjust context length based on model
        max_context_turns = 2 if model == "gpt-5-mini" else 1

        context_parts = []
        recent_turns = list(self.turns)[-max_context_turns:]

        for turn in recent_turns:
            # Only include recent context (last 5 minutes)
            if time.time() - turn.timestamp < 300:
                context_parts.append(f"Utilisateur précédent: {turn.user_input}")
                context_parts.append(f"Ta réponse précédente: {turn.ai_response}")

        if context_parts:
            return "\n".join(context_parts)
        return ""

    def clear_old_context(self, max_age_seconds: int = 600) -> None:
        """Clear context older than max_age_seconds"""
        current_time = time.time()

        # Remove old turns
        while self.turns and (current_time - self.turns[0].timestamp) > max_age_seconds:
            self.turns.popleft()

    def get_stats(self) -> Dict[str, Any]:
        """Get context statistics"""
        if not self.turns:
            return {"turn_count": 0, "oldest_turn_age": 0}

        current_time = time.time()
        oldest_turn_age = current_time - self.turns[0].timestamp if self.turns else 0

        return {
            "turn_count": len(self.turns),
            "oldest_turn_age": oldest_turn_age,
            "max_turns": self.max_turns,
        }

    def should_purge(self) -> bool:
        """Check if context should be purged due to inactivity"""
        if not self.turns:
            return False

        # Purge if last turn was more than 10 minutes ago
        last_turn_age = time.time() - self.turns[-1].timestamp
        return last_turn_age > 600

    def purge(self) -> None:
        """Clear all context"""
        self.turns.clear()


# Global context manager instance
context_manager = ContextManager()
