"""
Chatsee AI SDK
Tracks conversation data with optional support for tool calls, errors, and metadata.
"""

from typing import Optional, Dict, Any, List
from dataclasses import dataclass, asdict
from datetime import datetime
import requests
import logging
import warnings

# Set up a logger for the library
logger = logging.getLogger(__name__)

@dataclass
class ToolCall:
    tool_name: str
    arguments: Dict[str, Any]
    result: Optional[Any] = None
    error: Optional[str] = None
    timestamp: str = None
    
    def __post_init__(self):
        if self.timestamp is None:
            self.timestamp = datetime.utcnow().isoformat()

class ChatseeTracker:
    """
    SDK class for tracking LLM conversations.
    """
    
    _API_ENDPOINT = "https://demo-api.chatsee.ai:8000/v1/api/process_interaction"
    
    def __init__(self, 
                 agent_id: str,
                 tenant_id: str,
                 # Removed chatsee_api_key
                 session_id: Optional[str] = None,
                 timeout: int = 10,
                 verify_ssl: bool = False):
        
        if not agent_id or not tenant_id:
            raise ValueError("agent_id and tenant_id are required.")
            
        self.agent_id = agent_id
        self.tenant_id = tenant_id
        self.session_id = session_id 
        self.timeout = timeout
        self.verify_ssl = verify_ssl
        
        # Internal state for the current turn
        self.current_user_message: Optional[str] = None
        self.current_metadata: Dict[str, Any] = {}
        self.current_tool_calls: List[ToolCall] = []
        self.current_exception: Optional[str] = None
        self.error_encountered: int = 0
        
        self.session = requests.Session()
        self.session.headers.update({
            "Content-Type": "application/json"
        })
        
        if not self.verify_ssl:
            warnings.filterwarnings('ignore', 'Unverified HTTPS request')

    def start_turn(self, user_message: str, metadata: Optional[Dict[str, Any]] = None):
        """
        Start tracking a turn.
        """
        self.current_user_message = user_message
        self.current_metadata = metadata or {}
        self.current_tool_calls = []
        self.current_exception = None
        self.error_encountered = 0
    
    def log_tool_call(self, tool_name: str, arguments: Dict[str, Any], 
                      result: Optional[Any] = None, error: Optional[str] = None):
        """
        Log an optional tool/function call.
        """
        if self.current_user_message is None:
             logger.warning("log_tool_call called before start_turn.")
             return

        tool_call = ToolCall(
            tool_name=tool_name,
            arguments=arguments,
            result=result,
            error=error
        )
        self.current_tool_calls.append(tool_call)
        
        if error:
            self.error_encountered = 1
            if not self.current_exception:
                self.current_exception = error
    
    def log_exception(self, exception: Exception):
        """
        Log an optional exception.
        """
        if self.current_user_message is None:
             logger.warning("log_exception called before start_turn.")
             return

        self.error_encountered = 1
        self.current_exception = str(exception)
    
    def end_turn(self, bot_message: str):
        """
        Complete the turn and send data to the API.
        """
        if not self.current_user_message:
            logger.warning("end_turn called without start_turn. Skipping log.")
            return

        try:
            # Prepare optional tool call data
            tool_calls_dicts = [asdict(tc) for tc in self.current_tool_calls]
            
            payload = {
                # Required Fields (No API Key)
                'agent_id': self.agent_id,
                'tenant_id': self.tenant_id,
                'user_message': self.current_user_message,
                'bot_message': bot_message,
                'session_id': self.session_id,
                
                # Optional Fields
                'tool_call': 1 if tool_calls_dicts else 0,
                'tool_calls_details': tool_calls_dicts,
                'error_encountered': self.error_encountered,
                'exception': self.current_exception,
                'metadata': self.current_metadata
            }
            
            # Send to API
            response = self.session.post(
                self._API_ENDPOINT, 
                json=payload,
                timeout=self.timeout,
                verify=self.verify_ssl
            )
            response.raise_for_status()
            
            # Update session ID if generated by API
            if not self.session_id:
                data = response.json()
                if 'session_id' in data:
                    self.session_id = data['session_id']
            
        except Exception as e:
            logger.error(f"Failed to send turn to Chatsee: {e}")
        finally:
            # Reset state
            self.current_user_message = None
            self.current_metadata = {}
            self.current_tool_calls = []
            self.current_exception = None
            self.error_encountered = 0