"""
OpenAI Service
"""
from openai import OpenAI
from typing import Optional, List, Dict, Any
from app.core.config import settings
from app.services.llm_service import LLMService


def get_openai_client() -> OpenAI:
    """Get OpenAI client with API key from settings"""
    api_key = settings.OPENAI_API_KEY or ""
    if settings.llm_mode() != "qwen_only" and not api_key:
        raise ValueError("OPENAI_API_KEY environment variable is not set")
    return OpenAI(api_key=api_key)


def chat_completion(
    messages: List[Dict[str, str]],
    model: str = "gpt-3.5-turbo",
    temperature: float = 0.7,
    max_tokens: Optional[int] = None,
) -> str:
    """
    Send a chat completion request via LLMService (uses LLMService.DEFAULT_MODEL).

    Args:
        messages: List of message dicts with 'role' and 'content'
        model: Ignored; LLMService uses DEFAULT_MODEL
        temperature: Creativity parameter (0-2)
        max_tokens: Maximum tokens in response

    Returns:
        Response text from the model
    """
    api_key = settings.OPENAI_API_KEY or ""
    ck = (getattr(settings, "CLAUDE_API_KEY", None) or "").strip()
    if settings.llm_mode() != "qwen_only" and not (api_key or "").strip() and not ck:
        raise ValueError("OPENAI_API_KEY or CLAUDE_API_KEY must be set")
    llm = LLMService(api_key=api_key, claude_api_key=ck)
    return llm.chat_completion(
        messages=messages,
        temperature=temperature,
        max_tokens=max_tokens,
    )


def generate_sql(
    question: str,
    schema: str,
    model: str = "gpt-4",
) -> str:
    # model param kept for API compatibility; LLMService uses DEFAULT_MODEL
    """
    Generate SQL from natural language question
    
    Args:
        question: Natural language question
        schema: Database schema description
        model: OpenAI model to use
    
    Returns:
        Generated SQL query
    """
    messages = [
        {
            "role": "system",
            "content": f"""You are a SQL expert. Generate SQL queries based on the user's question.
            
Database Schema:
{schema}

Rules:
1. Return ONLY the SQL query, no explanations
2. Use proper SQL syntax
3. Handle NULL values appropriately
4. Use appropriate JOINs when needed"""
        },
        {
            "role": "user",
            "content": question
        }
    ]
    
    return chat_completion(messages, model=model, temperature=0)


def generate_chart_config(
    question: str,
    data_sample: str,
    model: str = "gpt-3.5-turbo",
) -> Dict[str, Any]:
    # model param kept for API compatibility; LLMService uses DEFAULT_MODEL
    """
    Generate chart configuration based on question and data
    
    Args:
        question: User's question
        data_sample: Sample of the data
        model: OpenAI model to use
    
    Returns:
        Chart configuration dict
    """
    import json
    
    messages = [
        {
            "role": "system",
            "content": """You are a data visualization expert. Based on the user's question and data sample, suggest the best chart type and configuration.

Return a JSON object with:
{
    "chart_type": "bar|line|pie|scatter|table",
    "title": "Chart title",
    "x_axis": "column name for x-axis",
    "y_axis": "column name for y-axis",
    "explanation": "Why this chart type is best"
}"""
        },
        {
            "role": "user",
            "content": f"Question: {question}\n\nData Sample:\n{data_sample}"
        }
    ]
    
    response = chat_completion(messages, model=model, temperature=0.3)
    
    try:
        return json.loads(response)
    except json.JSONDecodeError:
        return {"chart_type": "table", "explanation": "Could not parse chart config"}


def analyze_dataframe(
    df_json: List[Dict[str, Any]],
    question: str,
    model: str = "gpt-4",
) -> Dict[str, Any]:
    # model param kept for API compatibility; LLMService uses DEFAULT_MODEL
    """
    Analyze a pandas DataFrame with OpenAI
    
    Args:
        df_json: DataFrame as list of dicts (df.to_dict('records'))
        question: Analysis question
        model: OpenAI model to use
    
    Returns:
        Analysis result with answer and insights
    """
    import json
    
    # Get DataFrame info
    if df_json:
        columns = list(df_json[0].keys())
        num_rows = len(df_json)
        # Show sample (first 10 rows)
        sample = df_json[:10] if len(df_json) > 10 else df_json
    else:
        columns = []
        num_rows = 0
        sample = []
    
    messages = [
        {
            "role": "system",
            "content": """You are a data analyst expert. Analyze the given data and answer the user's question.

Provide your response as a JSON object with:
{
    "answer": "Direct answer to the question",
    "insights": ["List of key insights from the data"],
    "summary": "Brief summary of the analysis",
    "suggested_charts": ["bar", "line", "pie"],
    "code": "Optional Python/pandas code for further analysis"
}"""
        },
        {
            "role": "user",
            "content": f"""Question: {question}

Data Information:
- Columns: {columns}
- Total Rows: {num_rows}

Sample Data (first 10 rows):
{json.dumps(sample, indent=2, default=str)}"""
        }
    ]
    
    response = chat_completion(messages, model=model, temperature=0.3)
    
    try:
        return json.loads(response)
    except json.JSONDecodeError:
        return {"answer": response, "insights": [], "summary": "Raw response"}


def generate_question_summary(
    question: str,
    df_columns: List[str],
    model: str = "gpt-4",
    language: str = "English",
) -> str:
    # model param kept for API compatibility; LLMService uses DEFAULT_MODEL
    """
    Generate a summary of the results of a SQL query.
    
    Args:
        question: The question that was asked
        df_columns: List of DataFrame column names
        model: OpenAI model to use
        language: Response language
    
    Returns:
        Summary of the results
    """
    messages = [
        {
            "role": "system",
            "content": f"You are a helpful data assistant. The user asked the question: '{question}'\n\nThe following is a pandas DataFrame columns with the results of the query: \n{df_columns}\n\n"
        },
        {
            "role": "user",
            "content": f"Briefly summarize the data based on the question that was asked. Do not respond with any additional explanation beyond the summary. Respond in {language}."
        }
    ]
    
    return chat_completion(messages, model=model, temperature=0.3)


