"""Client-facing helpers for validating CyberLicensing keys."""

from __future__ import annotations

from typing import Dict, Optional

import requests

from .environment import collect_environment_metadata, get_machine_fingerprint, get_public_ip
from .exceptions import ApiError


class LicenseClient:
    """Simple wrapper for the public validation endpoint."""

    def __init__(self, base_url: str, timeout: float = 5.0):
        self.base_url = base_url.rstrip('/')
        self.timeout = timeout

    def validate_license(
        self,
        key: str,
        hwid: Optional[str] = None,
        ip: Optional[str] = None,
        metadata: Optional[Dict[str, str]] = None,
    ) -> Dict:
        payload: Dict[str, object] = {"key": key}
        if hwid:
            payload["hwid"] = hwid
        if ip:
            payload["ip"] = ip
        if metadata:
            payload["metadata"] = metadata

        response = requests.post(
            f"{self.base_url}/api/validate_license",
            json=payload,
            timeout=self.timeout,
        )
        if response.status_code >= 400:
            raise ApiError(response.status_code, response.text, response.json() if response.content else None)
        return response.json()

    def validate_with_environment(self, key: str, extra_metadata: Optional[Dict[str, str]] = None) -> Dict:
        metadata = collect_environment_metadata()
        merged_metadata = {**{k: v for k, v in metadata.items() if v is not None}, **(extra_metadata or {})}
        return self.validate_license(
            key=key,
            hwid=metadata.get("hwid"),
            ip=metadata.get("ip"),
            metadata=merged_metadata,
        )

    @staticmethod
    def get_default_hwid() -> str:
        return get_machine_fingerprint()

    @staticmethod
    def get_default_ip() -> Optional[str]:
        return get_public_ip()
