"""Server-side scan quota check via the Oncecheck API."""

from __future__ import annotations

import json
import urllib.error
import urllib.request
from typing import TypedDict


WEB_APP_URL = "https://oncecheck.com"


class QuotaResult(TypedDict):
    allowed: bool
    plan: str
    used: int
    limit: int


def check_scan_quota(access_token: str) -> QuotaResult:
    """Check scan quota with the server and consume a scan slot if allowed.

    Raises ConnectionError if the server is unreachable,
    PermissionError if the token is invalid/expired.
    """
    url = f"{WEB_APP_URL}/api/scan-check"
    req = urllib.request.Request(
        url,
        method="POST",
        headers={
            "Authorization": f"Bearer {access_token}",
            "Content-Type": "application/json",
        },
    )

    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            return json.loads(resp.read())
    except urllib.error.HTTPError as exc:
        if exc.code == 401:
            raise PermissionError("Token expired or invalid. Run `oncecheck login` to re-authenticate.")
        body = exc.read().decode(errors="replace")
        raise ConnectionError(f"Scan check failed ({exc.code}): {body}")
    except (urllib.error.URLError, TimeoutError, OSError) as exc:
        raise ConnectionError(f"Could not reach Oncecheck server: {exc}")
