"""
@RAG_CONTEXT
{
  "archivo": "src/rag_indexer/llm_client.py",
  "lineas": 96,
  "tokens_estimados": 828,
  "hash_contenido": "ee0edb059f0b07fb8982e6d120051d46fbd598d1436cb80931357e487b2dbf60",
  "creacion": "2026-03-04",
  "modificacion": "2026-03-05",
  "tags": [
    "ACTIVE_LLM",
    "requests",
    "re",
    "time",
    ".config",
    "json"
  ],
  "descripcion_corta": "",
  "descripcion_larga": ""
}
"""
import re
import json
import time
import requests
from .config import ACTIVE_LLM, USE_CODE_MODEL, API_KEYS, MODELS


def clean_json_response(text):
    match = re.search(r'\{.*\}', text, re.DOTALL)
    return match.group(0) if match else text


def get_llm_descriptions(code, filename):
    api_key = API_KEYS.get(ACTIVE_LLM)
    tier = "code" if USE_CODE_MODEL else "default"
    model = MODELS.get(ACTIVE_LLM, {}).get(tier)

    if not api_key or not model:
        return "", ""

    prompt = (
        f"Eres un Analista de Arquitectura. Analiza el código de '{filename}'. "
        f"Devuelve ÚNICAMENTE un JSON válido sin markdown: "
        f'{{ "descripcion_corta": "Máx 50 chars.", "descripcion_larga": "100-500 chars, técnico." }}'
        f"\nCódigo:\n{code[:4000]}"
    )

    try:
        if ACTIVE_LLM in ["openai", "deepseek"]:
            url = (
                "https://api.openai.com/v1/chat/completions"
                if ACTIVE_LLM == "openai"
                else "https://api.deepseek.com/chat/completions"
            )
            headers = {
                "Authorization": f"Bearer {api_key}",
                "Content-Type": "application/json"
            }
            payload = {
                "model": model,
                "messages": [{"role": "user", "content": prompt}],
                "response_format": {"type": "json_object"}
            }
            res = requests.post(url, json=payload, headers=headers, timeout=30)
            res.raise_for_status()
            response_text = res.json()['choices'][0]['message']['content']

        elif ACTIVE_LLM == "anthropic":
            headers = {
                "x-api-key": api_key,
                "anthropic-version": "2023-06-01",
                "content-type": "application/json"
            }
            payload = {
                "model": model,
                "max_tokens": 500,
                "messages": [{"role": "user", "content": prompt}]
            }
            res = requests.post(
                "https://api.anthropic.com/v1/messages",
                json=payload,
                headers=headers,
                timeout=30
            )
            res.raise_for_status()
            response_text = res.json()['content'][0]['text']

        elif ACTIVE_LLM == "gemini":
            url = (
                f"https://generativelanguage.googleapis.com/v1beta/models"
                f"/{model}:generateContent?key={api_key}"
            )
            payload = {
                "contents": [{"parts": [{"text": prompt}]}],
                "generationConfig": {"responseMimeType": "application/json"}
            }
            res = requests.post(
                url,
                json=payload,
                headers={"Content-Type": "application/json"},
                timeout=30
            )
            res.raise_for_status()
            response_text = res.json()['candidates'][0]['content']['parts'][0]['text']

        else:
            print(f"LLM no soportado: {ACTIVE_LLM}")
            return "", ""

        time.sleep(1.5)
        result = json.loads(clean_json_response(response_text))
        return result.get("descripcion_corta", ""), result.get("descripcion_larga", "")

    except Exception as e:
        print(f"Error LLM ({ACTIVE_LLM}): {e}")
        return "", ""
