import json
import re
from typing import Optional
import httpx
from loguru import logger
from tenacity import retry, stop_after_attempt, wait_exponential
from app.config import settings

OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1"

MINERS_PROMPT = """
Return a JSON array of exactly 45 cryptocurrency mining devices sorted by hashrate (descending).
Include both ASIC miners and high-end GPUs.

Each object must have these exact fields:
{
  "name": "device full name (lowercase)",
  "brand": "manufacturer name",
  "type": "ASIC" or "GPU",
  "hashrate": numeric value in TH/s (convert MH/s → TH/s, GH/s → TH/s),
  "hashrate_unit": "TH/s",
  "power_consumption": integer in Watts,
  "efficiency": J/TH ratio as float,
  "supported_coins": "BTC,ETH,LTC" (comma-separated coin symbols)
}

Rules:
- hashrate must be a pure number in TH/s units
- power_consumption must be an integer (Watts)
- efficiency = power_consumption / hashrate
- supported_coins must be real coins this device can mine
- Sort by hashrate descending
- Return ONLY the JSON array, no explanation, no markdown

Example entry:
{"name": "antminer s21 pro", "brand": "Bitmain", "type": "ASIC", "hashrate": 234.0, "hashrate_unit": "TH/s", "power_consumption": 3531, "efficiency": 15.09, "supported_coins": "BTC,BCH,BSV"}
"""


@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
async def fetch_miners_from_ai() -> list[dict]:
    if not settings.openrouter_api_key:
        logger.warning("OpenRouter API key not set, using fallback data")
        return _get_fallback_miners()

    headers = {
        "Authorization": f"Bearer {settings.openrouter_api_key}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://crypto-mining-system.local",
        "X-Title": "Crypto Mining Profitability System",
    }

    payload = {
        "model": settings.openrouter_model,
        "messages": [
            {
                "role": "system",
                "content": "You are a cryptocurrency mining hardware expert. Return only valid JSON arrays.",
            },
            {"role": "user", "content": MINERS_PROMPT},
        ],
        "temperature": 0.1,
        "max_tokens": 8000,
    }

    async with httpx.AsyncClient(timeout=60.0) as client:
        response = await client.post(
            f"{OPENROUTER_BASE_URL}/chat/completions",
            headers=headers,
            json=payload,
        )
        response.raise_for_status()
        data = response.json()

    content = data["choices"][0]["message"]["content"].strip()
    miners = _parse_json_response(content)

    if not miners:
        logger.warning("AI returned empty or invalid data, using fallback")
        return _get_fallback_miners()

    logger.info(f"Fetched {len(miners)} miners from OpenRouter AI")
    return miners


@retry(stop=stop_after_attempt(3), wait=wait_exponential(multiplier=1, min=2, max=10))
async def get_ai_recommendation(
    coin: str,
    electricity_price: float,
    budget: Optional[float],
    miners: list[dict],
) -> dict:
    if not settings.openrouter_api_key:
        return {"recommendation": "AI unavailable", "reason": "No API key configured"}

    miners_summary = json.dumps(miners[:10], ensure_ascii=False)

    prompt = f"""
You are a crypto mining profitability expert.

User wants to mine: {coin}
Electricity price: {electricity_price} SAR/kWh
Budget: {budget or 'Not specified'} SAR

Top miners available:
{miners_summary}

Analyze and recommend the BEST miner. Consider:
1. Profitability (revenue - electricity cost)
2. Efficiency (J/TH)
3. ROI period
4. Coin compatibility

Return a JSON object:
{{
  "recommended_miner": "miner name",
  "reason": "brief explanation in Arabic",
  "estimated_monthly_profit": number,
  "roi_months": number,
  "tips": ["tip1", "tip2"]
}}
Return ONLY the JSON object.
"""

    headers = {
        "Authorization": f"Bearer {settings.openrouter_api_key}",
        "Content-Type": "application/json",
        "HTTP-Referer": "https://crypto-mining-system.local",
        "X-Title": "Crypto Mining Profitability System",
    }

    payload = {
        "model": settings.openrouter_model,
        "messages": [{"role": "user", "content": prompt}],
        "temperature": 0.3,
        "max_tokens": 1000,
    }

    async with httpx.AsyncClient(timeout=30.0) as client:
        response = await client.post(
            f"{OPENROUTER_BASE_URL}/chat/completions",
            headers=headers,
            json=payload,
        )
        response.raise_for_status()
        data = response.json()

    content = data["choices"][0]["message"]["content"].strip()
    result = _parse_json_response(content)
    return result if isinstance(result, dict) else {"recommendation": content}


def _parse_json_response(content: str) -> any:
    # Remove markdown code blocks if present
    content = re.sub(r"```(?:json)?", "", content).strip()

    # Find JSON array or object
    for pattern in [r"\[[\s\S]*\]", r"\{[\s\S]*\}"]:
        match = re.search(pattern, content)
        if match:
            try:
                return json.loads(match.group())
            except json.JSONDecodeError:
                continue

    try:
        return json.loads(content)
    except json.JSONDecodeError as e:
        logger.error(f"Failed to parse AI JSON response: {e}")
        return None


def _get_fallback_miners() -> list[dict]:
    return [
        {"name": "antminer s21 pro", "brand": "Bitmain", "type": "ASIC", "hashrate": 234.0, "hashrate_unit": "TH/s", "power_consumption": 3531, "efficiency": 15.09, "supported_coins": "BTC,BCH,BSV"},
        {"name": "antminer s21", "brand": "Bitmain", "type": "ASIC", "hashrate": 200.0, "hashrate_unit": "TH/s", "power_consumption": 3500, "efficiency": 17.5, "supported_coins": "BTC,BCH,BSV"},
        {"name": "whatsminer m60s", "brand": "MicroBT", "type": "ASIC", "hashrate": 186.0, "hashrate_unit": "TH/s", "power_consumption": 3441, "efficiency": 18.5, "supported_coins": "BTC,BCH"},
        {"name": "antminer s19 xp hyd", "brand": "Bitmain", "type": "ASIC", "hashrate": 257.0, "hashrate_unit": "TH/s", "power_consumption": 5326, "efficiency": 20.72, "supported_coins": "BTC,BCH,BSV"},
        {"name": "whatsminer m50s++", "brand": "MicroBT", "type": "ASIC", "hashrate": 148.0, "hashrate_unit": "TH/s", "power_consumption": 3306, "efficiency": 22.34, "supported_coins": "BTC,BCH"},
        {"name": "antminer s19 pro+", "brand": "Bitmain", "type": "ASIC", "hashrate": 120.0, "hashrate_unit": "TH/s", "power_consumption": 3360, "efficiency": 28.0, "supported_coins": "BTC,BCH,BSV"},
        {"name": "avalon made a15", "brand": "Canaan", "type": "ASIC", "hashrate": 150.0, "hashrate_unit": "TH/s", "power_consumption": 3400, "efficiency": 22.67, "supported_coins": "BTC,BCH"},
        {"name": "antminer l9", "brand": "Bitmain", "type": "ASIC", "hashrate": 16.0, "hashrate_unit": "TH/s", "power_consumption": 3360, "efficiency": 210.0, "supported_coins": "LTC,DOGE"},
        {"name": "antminer l7", "brand": "Bitmain", "type": "ASIC", "hashrate": 9.5, "hashrate_unit": "TH/s", "power_consumption": 3425, "efficiency": 360.5, "supported_coins": "LTC,DOGE"},
        {"name": "goldshell kd-box pro", "brand": "Goldshell", "type": "ASIC", "hashrate": 2.6, "hashrate_unit": "TH/s", "power_consumption": 230, "efficiency": 88.5, "supported_coins": "KDA"},
        {"name": "nvidia rtx 4090", "brand": "NVIDIA", "type": "GPU", "hashrate": 0.000133, "hashrate_unit": "TH/s", "power_consumption": 350, "efficiency": 2631579.0, "supported_coins": "ETH,RVN,ERGO,FLUX"},
        {"name": "nvidia rtx 3090 ti", "brand": "NVIDIA", "type": "GPU", "hashrate": 0.000120, "hashrate_unit": "TH/s", "power_consumption": 450, "efficiency": 3750000.0, "supported_coins": "ETH,RVN,ERGO"},
        {"name": "amd radeon rx 7900 xtx", "brand": "AMD", "type": "GPU", "hashrate": 0.000095, "hashrate_unit": "TH/s", "power_consumption": 355, "efficiency": 3736842.0, "supported_coins": "ETH,RVN,ERGO"},
        {"name": "nvidia rtx 3080 ti", "brand": "NVIDIA", "type": "GPU", "hashrate": 0.000118, "hashrate_unit": "TH/s", "power_consumption": 340, "efficiency": 2881355.0, "supported_coins": "ETH,RVN,ERGO"},
        {"name": "antminer e9 pro", "brand": "Bitmain", "type": "ASIC", "hashrate": 3.68, "hashrate_unit": "TH/s", "power_consumption": 2556, "efficiency": 694.6, "supported_coins": "ETH,ETC"},
    ]
