import time
import uuid
import requests
import urllib3

from storage import load_config

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

_CATALOG_CACHE = {"ts": 0, "products": []}

CATEGORIES = [
    ("ai", "🤖 AI & Agents"),
    ("vpn", "🛡️ VPN & Privacy"),
    ("streaming", "🎬 Streaming & Media"),
    ("software", "💻 Software & Design"),
    ("edukasi", "🎓 Education & Courses"),
    ("cloud", "☁️ Cloud & VPS"),
    ("gaming", "🎮 Gaming & Music"),
    ("other", "📦 Digital Services")
]


def classify_product(name):
    low = (name or "").lower()
    if any(k in low for k in ["gpt", "claude", "gemini", "grok", "perplexity", "cursor", "midjourney", "eleven", "lovable", "bolt", "replit", "runway", "kling", "hailuo", "suno", "udio", "poe", "copilot", "ai ", "codex", "api "]):
        return "ai"
    if any(k in low for k in ["vpn", "nord", "surfshark", "expressvpn", "hma", "mullvad", "proton", "proxy", "ipvanish"]):
        return "vpn"
    if any(k in low for k in ["netflix", "prime video", "disney", "crunchyroll", "youtube", "iptv", "hbo", "paramount", "apple tv"]):
        return "streaming"
    if any(k in low for k in ["canva", "adobe", "capcut", "figma", "notion", "microsoft", "office", "windows", "autodesk", "coreldraw", "picsart", "framer", "ilovepdf", "grammarly", "quillbot", "tradingview", "linkedin"]):
        return "software"
    if any(k in low for k in ["coursera", "udemy", "duolingo", "edx", "chegg", "skillshare", "brilliant", "datacamp", "scribd"]):
        return "edukasi"
    if any(k in low for k in ["cloud", "vps", "aws", "azure", "digitalocean", "railway", "sentry", "warp", "google cloud", "oracle"]):
        return "cloud"
    if any(k in low for k in ["spotify", "deezer", "tidal", "apple music", "discord", "nitro", "steam", "xbox", "playstation", "game"]):
        return "gaming"
    return "other"


def _headers():
    cfg = load_config()
    return {
        "Authorization": f"Bearer {cfg.get('aitool_key', '')}",
        "User-Agent": "NovaDigitalBot/1.0",
        "Content-Type": "application/json"
    }


def _base_url():
    cfg = load_config()
    return cfg.get("aitool_api", "https://aitoolshop.aitoolifystudio.io/api/reseller/v1").rstrip("/")


def fetch_catalog(force=False, ttl=45):
    now = time.time()
    if not force and _CATALOG_CACHE["products"] and (now - _CATALOG_CACHE["ts"]) < ttl:
        return _CATALOG_CACHE["products"]

    cfg = load_config()
    margin = 1.0 + (float(cfg.get("profit_margin", 30)) / 100.0)

    r = requests.get(f"{_base_url()}/products", headers=_headers(), timeout=15, verify=False)
    r.raise_for_status()
    raw = r.json()
    items = raw.get("products", []) if isinstance(raw, dict) else (raw if isinstance(raw, list) else [])

    enriched = []
    for p in items:
        cost = float(p.get("your_cost") or p.get("price_usdt") or 0.0)
        sell_price = round(cost * margin, 2) if cost > 0 else 0.99
        stock = p.get("stock")
        is_unlimited = bool(p.get("is_unlimited", False))
        in_stock = is_unlimited or (stock is not None and int(stock) > 0)
        enriched.append({
            "id": p.get("id"),
            "name": (p.get("name") or "").strip(),
            "cost": cost,
            "price": sell_price,
            "stock": 99 if is_unlimited else int(stock or 0),
            "is_unlimited": is_unlimited,
            "in_stock": in_stock,
            "category": classify_product(p.get("name", "")),
            "description": (p.get("description") or "").strip()
        })

    _CATALOG_CACHE["products"] = enriched
    _CATALOG_CACHE["ts"] = now
    return enriched


def get_product_by_id(pid, force=False):
    prods = fetch_catalog(force=force)
    for p in prods:
        if str(p.get("id")) == str(pid):
            return p
    return None


def place_supplier_order(product_id, quantity=1, customer_email=""):
    idem = f"tg_{product_id}_{int(time.time())}_{uuid.uuid4().hex[:6]}"
    payload = {
        "product_id": int(product_id),
        "quantity": int(quantity),
        "idempotency_key": idem
    }
    if customer_email:
        payload["customer_email"] = customer_email.strip()

    try:
        r = requests.post(f"{_base_url()}/order", json=payload, headers=_headers(), timeout=25, verify=False)
        return r.json()
    except Exception as e:
        return {"success": False, "error": str(e)}


def get_supplier_balance():
    try:
        r = requests.get(f"{_base_url()}/me", headers=_headers(), timeout=12, verify=False)
        return r.json()
    except Exception as e:
        return {"success": False, "error": str(e)}


def extract_delivery_text(order_res):
    """Formats AiToolShop order response into clean, copy-ready delivery credentials."""
    if not isinstance(order_res, dict):
        return str(order_res)

    parts = []
    ref = order_res.get("order_ref") or order_res.get("reference") or order_res.get("id") or ""
    if ref:
        parts.append(f"Order Ref: <code>{ref}</code>")

    for key in ("delivered_items", "items", "accounts", "codes", "credentials", "lines", "data"):
        val = order_res.get(key)
        if isinstance(val, list) and val:
            formatted = []
            for idx, item in enumerate(val, 1):
                if isinstance(item, dict):
                    line = " | ".join(f"{k}: {v}" for k, v in item.items() if v)
                    formatted.append(f"{idx}. <code>{line}</code>")
                else:
                    formatted.append(f"{idx}. <code>{str(item)}</code>")
            parts.append("\n".join(formatted))
        elif isinstance(val, str) and val.strip():
            parts.append(f"<code>{val.strip()}</code>")
        elif isinstance(val, dict) and val:
            line = "\n".join(f"• <b>{k}:</b> <code>{v}</code>" for k, v in val.items() if v is not None)
            if line:
                parts.append(line)

    if len(parts) <= 1:
        # Fallback for direct top-level credential fields
        for k in ("credential", "account", "code", "token", "link", "message", "delivery"):
            if order_res.get(k):
                parts.append(f"<code>{order_res[k]}</code>")

    return "\n\n".join(parts) if parts else "Order confirmed! Check your order reference above."
