# vorto_utils/qrcode.py - QR code utility with multi-source fallback
import logging
from urllib.parse import quote as url_quote

import requests

logger = logging.getLogger(__name__)

# Self-hosted QR code API config (priority 1)
_SELF_API_BASE = "https://qrcode.vorto.cn"
_SELF_API_KEY = "4jpC3Cgd0zA7Z3HTJ6aDfW9QjtzitDGI"
_SELF_API_TIMEOUT = 8  # seconds

# qrtool.cn (priority 2)
_QRTOOL_API = "https://api.qrtool.cn/"
_QRTOOL_TIMEOUT = 5  # seconds

# qrserver.com - final fallback (priority 3)
_QRSERVER_API = "https://api.qrserver.com/v1/create-qr-code/"


def _generate_via_self_api(content):
    """Generate QR code URL via self-hosted API (qrcode.vorto.cn).

    Returns the image URL on success, None on failure.
    """
    try:
        resp = requests.get(
            f"{_SELF_API_BASE}/api/qrcode/generate",
            params={"content": content, "api_key": _SELF_API_KEY},
            timeout=_SELF_API_TIMEOUT,
        )
        if resp.status_code == 200:
            data = resp.json()
            if data.get("success") and data.get("data", {}).get("url"):
                return data["data"]["url"]
        logger.warning("Self-hosted QR API returned unexpected response: %s", resp.text)
    except Exception as e:
        logger.warning("Self-hosted QR API failed: %s", e)
    return None


def _generate_via_qrtool(content, size=300):
    """Generate QR code URL via api.qrtool.cn.

    Verifies availability with HEAD request before returning URL.
    Returns the image URL on success, None on failure.
    """
    encoded = url_quote(content)
    url = f"{_QRTOOL_API}?text={encoded}&size={size}&margin=20&level=H"
    try:
        resp = requests.head(url, timeout=_QRTOOL_TIMEOUT, allow_redirects=True)
        if resp.status_code == 200:
            return url
        logger.warning("qrtool.cn returned status %s", resp.status_code)
    except Exception as e:
        logger.warning("qrtool.cn failed: %s", e)
    return None


def _generate_via_qrserver(content, size="200x200"):
    """Generate QR code URL via qrserver.com (final fallback, no verification)."""
    encoded = url_quote(content)
    return f"{_QRSERVER_API}?size={size}&data={encoded}"


def generate_qrcode_url(content, size="200x200"):
    """Generate a QR code image URL for the given content.

    Fallback chain: self-hosted -> qrtool.cn -> qrserver.com
    Always returns a valid URL string.
    """
    # Priority 1: self-hosted
    url = _generate_via_self_api(content)
    if url:
        return url

    # Priority 2: qrtool.cn
    # Parse pixel size from "WxH" format for qrtool
    try:
        qrtool_size = int(size.split("x")[0])
    except (ValueError, AttributeError):
        qrtool_size = 300
    url = _generate_via_qrtool(content, size=qrtool_size)
    if url:
        logger.info("Using qrtool.cn for QR code generation")
        return url

    # Priority 3: qrserver.com (always works, no verification)
    logger.info("Falling back to qrserver.com for QR code generation")
    return _generate_via_qrserver(content, size)
