"""
Dashboard utilities for conversation management and confidence handling.
"""

import json
import uuid
from datetime import datetime
from typing import Dict, List, Optional
import os


class ConversationManager:
    """Manages conversation threads and their storage."""
    
    def __init__(self, storage_dir: str = "conversations"):
        self.storage_dir = storage_dir
        os.makedirs(storage_dir, exist_ok=True)
        self.conversations = {}
        self.load_conversations()
    
    def create_conversation(self, title: str = None) -> str:
        """Create a new conversation and return its ID."""
        conv_id = str(uuid.uuid4())
        title = title or f"New Chat {datetime.now().strftime('%Y-%m-%d %H:%M')}"
        
        conversation = {
            "id": conv_id,
            "title": title,
            "created_at": datetime.now().isoformat(),
            "updated_at": datetime.now().isoformat(),
            "messages": [],
            "model_settings": {
                "model_type": "llama",
                "confidence_threshold": 0.6,
                "temperature": 0.7,
                "max_tokens": 512
            }
        }
        
        self.conversations[conv_id] = conversation
        self.save_conversation(conv_id)
        return conv_id
    
    def add_message(self, conv_id: str, message: Dict) -> None:
        """Add a message to a conversation."""
        if conv_id in self.conversations:
            self.conversations[conv_id]["messages"].append(message)
            self.conversations[conv_id]["updated_at"] = datetime.now().isoformat()
            self.save_conversation(conv_id)
    
    def update_conversation_title(self, conv_id: str, title: str) -> None:
        """Update conversation title."""
        if conv_id in self.conversations:
            self.conversations[conv_id]["title"] = title
            self.conversations[conv_id]["updated_at"] = datetime.now().isoformat()
            self.save_conversation(conv_id)
    
    def update_model_settings(self, conv_id: str, settings: Dict) -> None:
        """Update model settings for a conversation."""
        if conv_id in self.conversations:
            self.conversations[conv_id]["model_settings"].update(settings)
            self.conversations[conv_id]["updated_at"] = datetime.now().isoformat()
            self.save_conversation(conv_id)
    
    def get_conversation(self, conv_id: str) -> Optional[Dict]:
        """Get a conversation by ID."""
        return self.conversations.get(conv_id)
    
    def get_conversation_list(self) -> List[Dict]:
        """Get list of all conversations sorted by update time."""
        conv_list = []
        for conv in self.conversations.values():
            conv_list.append({
                "id": conv["id"],
                "title": conv["title"],
                "updated_at": conv["updated_at"],
                "message_count": len(conv["messages"])
            })
        
        # Sort by updated_at descending
        conv_list.sort(key=lambda x: x["updated_at"], reverse=True)
        return conv_list
    
    def delete_conversation(self, conv_id: str) -> bool:
        """Delete a conversation."""
        if conv_id in self.conversations:
            del self.conversations[conv_id]
            conv_file = os.path.join(self.storage_dir, f"{conv_id}.json")
            if os.path.exists(conv_file):
                os.remove(conv_file)
            return True
        return False
    
    def save_conversation(self, conv_id: str) -> None:
        """Save a conversation to file."""
        if conv_id in self.conversations:
            conv_file = os.path.join(self.storage_dir, f"{conv_id}.json")
            with open(conv_file, 'w', encoding='utf-8') as f:
                json.dump(self.conversations[conv_id], f, indent=2, ensure_ascii=False)
    
    def load_conversations(self) -> None:
        """Load conversations from storage directory."""
        if not os.path.exists(self.storage_dir):
            return
        
        for filename in os.listdir(self.storage_dir):
            if filename.endswith('.json'):
                conv_id = filename[:-5]  # Remove .json extension
                conv_file = os.path.join(self.storage_dir, filename)
                try:
                    with open(conv_file, 'r', encoding='utf-8') as f:
                        conversation = json.load(f)
                        self.conversations[conv_id] = conversation
                except Exception as e:
                    print(f"Error loading conversation {conv_id}: {e}")


def format_confidence_message(confidence_score: float, threshold: float = 0.6) -> str:
    """Format a message when confidence is below threshold."""
    if confidence_score < threshold:
        return (
            f"I don't know the answer to that question with sufficient confidence "
            f"(confidence: {confidence_score:.2f} < {threshold:.2f}). "
            f"You should search the web for accurate information or consult other reliable sources."
        )
    return ""


def generate_conversation_title(first_message: str, max_length: int = 50) -> str:
    """Generate a conversation title from the first message."""
    if not first_message:
        return f"New Chat {datetime.now().strftime('%Y-%m-%d %H:%M')}"
    
    # Clean and truncate the message
    title = first_message.strip()
    if len(title) > max_length:
        title = title[:max_length-3] + "..."
    
    # Remove newlines and extra spaces
    title = " ".join(title.split())
    
    return title or f"New Chat {datetime.now().strftime('%Y-%m-%d %H:%M')}"