"""
Cursor Rules Generator - OpenAI Adapter

This module implements the LLM adapter for OpenAI API.
"""

import json
import requests
from typing import Dict, List, Optional, Any

from ..config.settings import Settings
from .adapter import LLMAdapter

class OpenAIAdapter(LLMAdapter):
    """Adapter for OpenAI API."""
    
    def __init__(self):
        """Initialize the OpenAI adapter."""
        self.api_key = None
        self.api_url = Settings.OPENAI_API_URL
        self.initialized = False
    
    def initialize(self, api_key: str, **kwargs) -> None:
        """Initialize the adapter with API key and optional parameters.
        
        Args:
            api_key: The OpenAI API key
            **kwargs: Additional provider-specific parameters
        """
        self.api_key = api_key
        self.api_url = kwargs.get('api_url', Settings.OPENAI_API_URL)
        self.initialized = True
    
    def validate_api_key(self, api_key: str) -> bool:
        """Validate the OpenAI API key.
        
        Args:
            api_key: The API key to validate
            
        Returns:
            bool: True if the API key is valid, False otherwise
        """
        try:
            # Try to list models with the provided API key
            url = f"{self.api_url}/models"
            headers = {
                "Authorization": f"Bearer {api_key}"
            }
            response = requests.get(url, headers=headers)
            
            # Check if the request was successful
            if response.status_code == 200:
                return True
            return False
        except Exception:
            return False
    
    def get_available_models(self) -> List[Dict[str, str]]:
        """Get a list of available OpenAI models.
        
        Returns:
            List[Dict[str, str]]: A list of model information dictionaries
        """
        if not self.initialized:
            raise ValueError("Adapter not initialized. Call initialize() first.")
        
        try:
            # Get available models
            url = f"{self.api_url}/models"
            headers = {
                "Authorization": f"Bearer {self.api_key}"
            }
            response = requests.get(url, headers=headers)
            
            if response.status_code != 200:
                raise ValueError(f"Failed to get models: {response.text}")
            
            data = response.json()
            
            # Filter for chat models and format the response
            models = []
            for model in data.get('data', []):
                model_id = model.get('id')
                if any(prefix in model_id for prefix in ['gpt-4', 'gpt-3.5']):
                    models.append({
                        'id': model_id,
                        'name': self._format_model_name(model_id)
                    })
            
            # If no models found, return default models
            if not models:
                models = [
                    {'id': 'gpt-4o', 'name': 'GPT-4o'},
                    {'id': 'gpt-4-turbo', 'name': 'GPT-4 Turbo'},
                    {'id': 'gpt-3.5-turbo', 'name': 'GPT-3.5 Turbo'}
                ]
            
            return models
        except Exception as e:
            # Return default models on error
            return [
                {'id': 'gpt-4o', 'name': 'GPT-4o'},
                {'id': 'gpt-4-turbo', 'name': 'GPT-4 Turbo'},
                {'id': 'gpt-3.5-turbo', 'name': 'GPT-3.5 Turbo'}
            ]
    
    def generate_rule(
        self, 
        model: str,
        rule_type: str, 
        description: str, 
        content: str, 
        parameters: Optional[Dict[str, Any]] = None
    ) -> str:
        """Generate a Cursor Rule using OpenAI.
        
        Args:
            model: The OpenAI model ID to use
            rule_type: The type of rule to generate
            description: A short description of the rule's purpose
            content: The main content of the rule
            parameters: Additional parameters for rule generation
                
        Returns:
            str: The generated rule in MDC format
        """
        if not self.initialized:
            raise ValueError("Adapter not initialized. Call initialize() first.")
        
        # Set default parameters if not provided
        if parameters is None:
            parameters = {}
        
        # Extract parameters
        temperature = parameters.get('temperature', Settings.DEFAULT_TEMPERATURE)
        globs = parameters.get('globs', '')
        referenced_files = parameters.get('referenced_files', '')
        prompt = parameters.get('prompt', '')
        
        # Prepare the prompt for OpenAI
        system_prompt = """
        You are a Cursor Rules expert. Create a rule in MDC format based on the provided information.
        
        MDC format example:
        ---
        description: RPC Service boilerplate
        globs: 
        alwaysApply: false
        ---
        
        - Use our internal RPC pattern when defining services
        - Always use snake_case for service names.
        
        @service-template.ts
        """
        
        user_prompt = f"""
        Create a Cursor Rule with the following details:
        
        Rule Type: {rule_type}
        Description: {description}
        Content: {content}
        """
        
        if globs:
            user_prompt += f"\nGlobs: {globs}"
        
        if referenced_files:
            user_prompt += f"\nReferenced Files: {referenced_files}"
        
        if prompt:
            user_prompt += f"\nAdditional Instructions: {prompt}"
        
        # Prepare the API request
        url = f"{self.api_url}/chat/completions"
        headers = {
            "Authorization": f"Bearer {self.api_key}",
            "Content-Type": "application/json"
        }
        
        payload = {
            "model": model,
            "messages": [
                {
                    "role": "system",
                    "content": system_prompt
                },
                {
                    "role": "user",
                    "content": user_prompt
                }
            ],
            "temperature": temperature,
            "max_tokens": 2048
        }
        
        # Make the API request
        try:
            response = requests.post(url, headers=headers, json=payload)
            
            if response.status_code != 200:
                raise ValueError(f"Failed to generate rule: {response.text}")
            
            data = response.json()
            
            # Extract the generated text
            generated_text = data.get('choices', [{}])[0].get('message', {}).get('content', '')
            
            # If no text was generated, create a basic rule
            if not generated_text:
                return self._create_basic_rule(rule_type, description, content, globs, referenced_files)
            
            return generated_text
        except Exception as e:
            # Create a basic rule on error
            return self._create_basic_rule(rule_type, description, content, globs, referenced_files)
    
    def _format_model_name(self, model_id: str) -> str:
        """Format a model ID into a human-readable name.
        
        Args:
            model_id: The model ID
            
        Returns:
            str: A human-readable model name
        """
        # Replace hyphens with spaces and capitalize each word
        name = model_id.replace('-', ' ').title()
        
        # Special case handling
        name = name.replace('Gpt ', 'GPT ')
        name = name.replace('Gpt4', 'GPT-4')
        name = name.replace('Gpt3', 'GPT-3')
        name = name.replace('Gpt 4', 'GPT-4')
        name = name.replace('Gpt 3', 'GPT-3')
        name = name.replace('Turbo', 'Turbo')
        name = name.replace('O', 'o')
        
        return name
    
    def _create_basic_rule(
        self,
        rule_type: str,
        description: str,
        content: str,
        globs: str = '',
        referenced_files: str = ''
    ) -> str:
        """Create a basic rule in MDC format without using the LLM.
        
        Args:
            rule_type: The type of rule
            description: The rule description
            content: The rule content
            globs: Glob patterns for Auto Attached rules
            referenced_files: Referenced files
            
        Returns:
            str: The rule in MDC format
        """
        # Create MDC format
        mdc = '---\n'
        mdc += f'description: {description}\n'
        
        if rule_type == 'Auto Attached' and globs:
            mdc += f'globs: {globs}\n'
        
        if rule_type == 'Always':
            mdc += 'alwaysApply: true\n'
        else:
            mdc += 'alwaysApply: false\n'
        
        mdc += '---\n\n'
        mdc += content + '\n'
        
        # Add referenced files
        if referenced_files:
            mdc += '\n' + referenced_files
        
        return mdc