"""LLM client for SolAgent-FHE. Supports DeepSeek, Groq via OpenAI-compatible API."""

import os
import re
import httpx


def get_api_config(model: str = "deepseek") -> dict:
    """Get API configuration for the specified model provider."""
    configs = {
        "deepseek": {
            "base_url": "https://api.deepseek.com/v1",
            "api_key": os.environ.get("DEEPSEEK_API_KEY", ""),
            "model": "deepseek-chat",
        },
        "groq": {
            "base_url": "http://localhost:11435/v1",
            "api_key": "groq-proxy",  # Groq proxy handles 100 keys rotation
            "model": "llama-3.3-70b-versatile",
        },
    }
    return configs.get(model, configs["deepseek"])


async def chat(messages: list, provider: str = "deepseek", temperature: float = 0.2) -> str:
    """Send chat completion request. Returns assistant message content."""
    config = get_api_config(provider)

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {config['api_key']}",
    }

    payload = {
        "model": config["model"],
        "messages": messages,
        "temperature": temperature,
        "max_tokens": 8192,
    }

    async with httpx.AsyncClient(timeout=120) as client:
        resp = await client.post(
            f"{config['base_url']}/chat/completions",
            headers=headers,
            json=payload,
        )
        resp.raise_for_status()
        data = resp.json()
        return data["choices"][0]["message"]["content"]


def extract_solidity(text: str) -> str:
    """Extract Solidity code from LLM response."""
    match = re.search(r'```solidity\s*\n(.*?)```', text, re.DOTALL)
    if match:
        return match.group(1).strip()

    match = re.search(r'```sol\s*\n(.*?)```', text, re.DOTALL)
    if match:
        return match.group(1).strip()

    match = re.search(r'```\s*\n(.*?pragma.*?)```', text, re.DOTALL)
    if match:
        return match.group(1).strip()

    match = re.search(r'(// SPDX.*?$.*?pragma solidity.*)', text, re.DOTALL | re.MULTILINE)
    if match:
        return match.group(1).strip()

    return text.strip()
