"""CapSolver API client — reCAPTCHA v2 and v3."""
from __future__ import annotations

import json
import time
import urllib.request


def _capsolver_request(url: str, payload: dict) -> dict:
    data = json.dumps(payload).encode()
    req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=30) as resp:
        return json.loads(resp.read())


def create_task(api_key: str, task: dict) -> str | None:
    result = _capsolver_request("https://api.capsolver.com/createTask", {
        "clientKey": api_key,
        "task": task,
    })
    if result.get("errorId", 0) != 0:
        print(f"[capsolver] createTask error: {result}", flush=True)
        return None
    return result["taskId"]


def poll_task(api_key: str, task_id: str, max_attempts: int = 40, interval: float = 3.0) -> str | None:
    """Poll until ready. Returns gRecaptchaResponse token or None."""
    for _ in range(max_attempts):
        time.sleep(interval)
        result = _capsolver_request("https://api.capsolver.com/getTaskResult", {
            "clientKey": api_key,
            "taskId": task_id,
        })
        status = result.get("status", "")
        if status == "ready":
            return result["solution"]["gRecaptchaResponse"]
        if status == "failed":
            print(f"[capsolver] Task failed: {result}", flush=True)
            return None
    print("[capsolver] Timeout", flush=True)
    return None


def solve_v2(api_key: str, page_url: str, sitekey: str) -> str | None:
    task_id = create_task(api_key, {
        "type": "ReCaptchaV2TaskProxyLess",
        "websiteURL": page_url,
        "websiteKey": sitekey,
    })
    return poll_task(api_key, task_id) if task_id else None


def solve_v3_proxyless(api_key: str, page_url: str, sitekey: str, action: str, min_score: float = 0.9) -> str | None:
    task_id = create_task(api_key, {
        "type": "ReCaptchaV3TaskProxyLess",
        "websiteURL": page_url,
        "websiteKey": sitekey,
        "pageAction": action,
        "minScore": min_score,
    })
    return poll_task(api_key, task_id) if task_id else None


def solve_v3_proxy(api_key: str, page_url: str, sitekey: str, action: str, proxy_str: str, min_score: float = 0.9) -> str | None:
    """proxy_str format: 'socks5:host:port:user:pass'"""
    task_id = create_task(api_key, {
        "type": "ReCaptchaV3Task",
        "websiteURL": page_url,
        "websiteKey": sitekey,
        "pageAction": action,
        "minScore": min_score,
        "proxy": proxy_str,
    })
    return poll_task(api_key, task_id) if task_id else None
