"""
SocialFastMM API v2 client — standalone module (no Flask imports).
Docs: https://socialfastmm.com/api
"""

from __future__ import annotations

import os
from typing import Any

import requests


def _api_url() -> str:
    return (os.getenv("SOCIAL_BOOSTING_API_URL") or "https://socialfastmm.com/api/v2").strip().rstrip("/")


def _api_key() -> str:
    return (os.getenv("SOCIAL_BOOSTING_API_KEY") or "").strip()


def post_action(action: str, **extra: Any) -> dict[str, Any] | list[Any]:
    """
    POST form body: key, action, ... per panel API.
    Returns parsed JSON (dict or list) or {"error": "..."}.
    """
    key = _api_key()
    if not key:
        return {"error": "SOCIAL_BOOSTING_API_KEY is not set in .env"}

    url = _api_url()
    data: dict[str, Any] = {"key": key, "action": action}
    data.update(extra)

    try:
        r = requests.post(url, data=data, timeout=60)
        r.raise_for_status()
    except requests.RequestException as e:
        return {"error": str(e)[:220]}

    try:
        out = r.json()
    except ValueError:
        return {"error": "Invalid JSON from provider"}

    if isinstance(out, dict) and out.get("error"):
        return {"error": str(out["error"])[:500]}
    return out


def get_balance() -> dict[str, Any]:
    out = post_action("balance")
    if isinstance(out, dict) and "error" in out:
        return out
    if isinstance(out, dict) and "balance" in out:
        return out
    return {"error": "Unexpected balance response"}


def get_services() -> list[dict[str, Any]] | dict[str, Any]:
    out = post_action("services")
    if isinstance(out, dict) and out.get("error"):
        return out
    if isinstance(out, list):
        return out
    if isinstance(out, dict):
        return {"error": out.get("error", "Unexpected services response")}
    return {"error": "Unexpected services response"}


def api_post_add(fields: dict[str, Any]) -> dict[str, Any] | list[Any]:
    """
    action=add — fields: service, link, and one of quantity / comments / username+quantity / answer_number (per panel docs).
    """
    key = _api_key()
    if not key:
        return {"error": "SOCIAL_BOOSTING_API_KEY is not set in .env"}
    url = _api_url()
    data: dict[str, Any] = {"key": key, "action": "add"}
    for k, v in fields.items():
        if v is None:
            continue
        data[k] = v

    try:
        r = requests.post(url, data=data, timeout=90)
        r.raise_for_status()
    except requests.RequestException as e:
        return {"error": str(e)[:220]}

    try:
        out = r.json()
    except ValueError:
        return {"error": "Invalid JSON from provider"}

    if isinstance(out, dict) and out.get("error"):
        return {"error": str(out["error"])[:500]}
    return out


def fetch_panel_snapshot() -> dict[str, Any]:
    """For the Social Boosting page: services list only (no reseller panel balance)."""
    snap: dict[str, Any] = {
        "services": [],
        "services_error": None,
        "services_total": 0,
    }

    # Default: return the full provider list. Older code sliced to 500, which hid
    # many platforms (e.g. YouTube / X / Threads) depending on API sort order.
    # Set SOCIAL_BOOSTING_SERVICES_MAX to a positive number to cap (e.g. 8000) if needed.
    try:
        max_svcs = int((os.getenv("SOCIAL_BOOSTING_SERVICES_MAX") or "0").strip() or "0")
    except ValueError:
        max_svcs = 0

    s = get_services()
    if isinstance(s, dict) and s.get("error"):
        snap["services_error"] = s["error"]
    elif isinstance(s, list):
        snap["services_total"] = len(s)
        if max_svcs > 0:
            snap["services"] = s[:max_svcs]
        else:
            snap["services"] = s

    return snap
