"""HTTP client for everflow-api-server PhotoPick license endpoints."""

from __future__ import annotations

import json
import urllib.error
import urllib.request
from typing import Any, Dict, Optional

from .. import config


class LicenseApiError(Exception):
    def __init__(self, message: str, *, code: str = "", status: int = 0):
        super().__init__(message)
        self.code = code
        self.status = status


def _api_base() -> str:
    return config.LICENSE_API_BASE.rstrip("/")


def _request(method: str, path: str, payload: Optional[dict] = None) -> Dict[str, Any]:
    url = f"{_api_base()}{path}"
    data = None
    headers = {"Accept": "application/json"}
    if payload is not None:
        data = json.dumps(payload).encode("utf-8")
        headers["Content-Type"] = "application/json"

    req = urllib.request.Request(url, data=data, headers=headers, method=method)
    try:
        with urllib.request.urlopen(req, timeout=30) as resp:
            body = resp.read().decode("utf-8")
            return json.loads(body) if body else {}
    except urllib.error.HTTPError as exc:
        message = exc.reason or "License API error"
        code = ""
        try:
            raw = exc.read().decode("utf-8")
            parsed = json.loads(raw)
            detail = parsed.get("detail")
            if isinstance(detail, dict):
                message = detail.get("message") or message
                code = detail.get("code") or ""
            elif isinstance(detail, str):
                message = detail
        except (OSError, json.JSONDecodeError, ValueError):
            pass
        raise LicenseApiError(message, code=code, status=exc.code) from exc
    except urllib.error.URLError as exc:
        raise LicenseApiError(f"Cannot reach license server: {exc.reason}") from exc


def activate(
    license_key: str,
    *,
    machine_id: str,
    device_name: Optional[str] = None,
    app_version: Optional[str] = None,
    arch: Optional[str] = None,
) -> Dict[str, Any]:
    return _request(
        "POST",
        "/photopick/license/activate",
        {
            "license_key": license_key,
            "machine_id": machine_id,
            "device_name": device_name,
            "app_version": app_version,
            "arch": arch,
        },
    )


def validate(
    license_key: str,
    *,
    machine_id: str,
    instance_id: Optional[str] = None,
) -> Dict[str, Any]:
    payload: Dict[str, Any] = {
        "license_key": license_key,
        "machine_id": machine_id,
    }
    if instance_id:
        payload["instance_id"] = instance_id
    return _request("POST", "/photopick/license/validate", payload)


def deactivate(
    license_key: str,
    *,
    machine_id: str,
    instance_id: Optional[str] = None,
) -> Dict[str, Any]:
    payload: Dict[str, Any] = {
        "license_key": license_key,
        "machine_id": machine_id,
    }
    if instance_id:
        payload["instance_id"] = instance_id
    return _request("POST", "/photopick/license/deactivate", payload)


def fetch_latest_release() -> Dict[str, Any]:
    return _request("GET", "/photopick/releases/latest")
