import os
import requests
import xbmcaddon
import xbmc
import json
import time
from wcs.ai.DialogAIDebugRequest import show_api_request_debug, show_api_response_debug, show_api_error_debug

# Funkce pro získání aktuálního modelu z nastavení
def get_current_model():
    """Vrací aktuálně vybraný OpenAI model z nastavení."""
    addon = xbmcaddon.Addon()
    selected_model = addon.getSetting("openai_model")
    if not selected_model:
        selected_model = "gpt-4.1"  # Výchozí model
    return selected_model

# Funkce pro odeslání promptu na OpenAI
def send_prompt(prompt: str, model: str = None, use_tools: bool = False, **kwargs) -> (str, dict):
    # Načtení nastavení addonu
    addon = xbmcaddon.Addon()
    API_KEY = addon.getSetting("openai_api_key")
    
    # Extra data pro debug
    context_titles = kwargs.get('context_titles')
    context_limit = kwargs.get('context_limit')
    
    if not API_KEY:
        raise ValueError("OpenAI API klíč není nastaven.")
    
    # Pokud není model specifikován, použij model z nastavení
    if model is None:
        model = get_current_model()
    
    # Načtení parametrů z nastavení
    temperature = float(addon.getSetting("openai_temperature") or "1.0")
    top_p = float(addon.getSetting("openai_top_p") or "1.0")
    max_output_tokens = int(addon.getSetting("openai_max_output_tokens") or "4096")
    
    url = "https://api.openai.com/v1/responses"
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
    }
    
    # GPT-5 modely používají verbosity a reasoning místo temperature/top_p
    is_gpt5_model = model.startswith("gpt-5")
    
    if is_gpt5_model:
        # Příprava reasoning effort podle modelu
        if model == "gpt-5-mini":
            reasoning_effort = "minimal"
        else:
            reasoning_effort = "none"
        
        payload = {
            "model": model,
            "input": [
                {"type": "message", "role": "user", "content": prompt}
            ],
            "text": {
                "verbosity": "low"
            },
            "reasoning": {
                "effort": reasoning_effort
            },
            "max_output_tokens": max_output_tokens
        }
    else:
        # Standardní modely (GPT-4.x a starší)
        payload = {
            "model": model,
            "input": [
                {"type": "message", "role": "user", "content": prompt}
            ],
            "temperature": temperature,
            "top_p": top_p,
            "max_output_tokens": max_output_tokens
        }
    
    # Přidat tools pouze pokud je to požadováno
    if use_tools:
        payload["tools"] = [{"type": "web_search_preview"}]
    xbmc.log(f"[wcs][openai] URL: {url}", getattr(xbmc, 'LOGNOTICE', xbmc.LOGINFO))
    xbmc.log(f"[wcs][openai] Model: {model}", getattr(xbmc, 'LOGNOTICE', xbmc.LOGINFO))
    xbmc.log(f"[wcs][openai] Prompt: {prompt}", getattr(xbmc, 'LOGNOTICE', xbmc.LOGINFO))
    xbmc.log(f"[wcs][openai] Payload: {json.dumps(payload)}", getattr(xbmc, 'LOGNOTICE', xbmc.LOGINFO))
    
    # Debug: Zobrazí raw request před odesláním
    if not show_api_request_debug("OpenAI", model, payload, context_titles=context_titles, context_limit=context_limit):
        raise Exception("Odeslání API requestu bylo zrušeno uživatelem.")
    
    start_time = time.time()
    response = requests.post(url, headers=headers, json=payload, timeout=120)
    end_time = time.time()
    latency = end_time - start_time
    xbmc.log(f"[wcs][openai] Raw response: {response.text}", getattr(xbmc, 'LOGNOTICE', xbmc.LOGINFO))
    
    # Debug: Zobrazí raw response po obdržení
    try:
        response_data = response.json()
        show_api_response_debug("OpenAI", model, response_data, latency=latency)
    except:
        show_api_response_debug("OpenAI", model, {"raw_text": response.text}, latency=latency)
    response.raise_for_status()
    data = response.json()
    # Extract usage data
    usage = data.get("usage", {})
    # Build content from output events
    outputs = data.get("output", [])
    content = ""
    if isinstance(outputs, list):
        for evt in outputs:
            if isinstance(evt, dict) and evt.get("type") == "message":
                cont = evt.get("content")
                if isinstance(cont, list):
                    # Combine segments text
                    content = "".join(seg.get("text", "") for seg in cont if isinstance(seg, dict))
                else:
                    content = cont or evt.get("text", "")
                break
    # Fallback to 'choices' if no output events
    if not content:
        content = data.get("choices", [{}])[0].get("message", {}).get("content", "")
    return content, usage

def validate_api_key():
    """
    Ověří platnost API klíče.
    
    Returns:
        bool: True pokud je klíč platný, False jinak
    """
    addon = xbmcaddon.Addon()
    API_KEY = addon.getSetting("openai_api_key")
    
    if not API_KEY:
        return False
    
    try:
        # Jednoduché volání pro ověření klíče
        url = "https://api.openai.com/v1/models"
        headers = {
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json",
        }
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        return True
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 401:
            xbmc.log("[wcs][openai_api] validate_api_key: Neplatný API klíč (401)", xbmc.LOGWARNING)
            return False
        else:
            xbmc.log(f"[wcs][openai_api] validate_api_key: HTTP chyba {e.response.status_code}", xbmc.LOGWARNING)
            return False
    except requests.exceptions.RequestException as e:
        xbmc.log(f"[wcs][openai_api] validate_api_key: Síťová chyba - {e}", xbmc.LOGWARNING)
        return False
    except Exception as e:
        xbmc.log(f"[wcs][openai_api] validate_api_key: Neočekávaná chyba - {e}", xbmc.LOGWARNING)
        return False 