"""Mesh device authentication — one-time token flow from phone."""

import json
import platform
import urllib.error
import urllib.request
from typing import Optional


def activate_with_token(
    token: str,
    api_url: str = "https://api.tinkclaw.com",
    device_name: Optional[str] = None,
    timeout: int = 15,
) -> dict:
    """Exchange a one-time token (from phone) for device credentials.

    The phone generates a token at /api/mesh/create-token.
    This device sends the token to /api/mesh/activate to register.

    Returns:
        {"device_id": "...", "auth_token": "...", "config": {...}}
    """
    if not device_name:
        device_name = f"{platform.node() or 'CLI'} ({platform.system()})"

    body = {
        "token": token,
        "device_name": device_name,
        "device_type": _detect_type(),
        "os": platform.platform(),
    }

    req = urllib.request.Request(
        f"{api_url.rstrip('/')}/api/mesh/activate",
        data=json.dumps(body).encode(),
        headers={"Content-Type": "application/json"},
        method="POST",
    )

    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        raw = e.read().decode()
        try:
            err = json.loads(raw)
        except (json.JSONDecodeError, ValueError):
            err = {"error": raw}
        raise RuntimeError(
            f"Activation failed ({e.code}): {err.get('error', raw)}"
        ) from None
    except urllib.error.URLError as e:
        raise RuntimeError(f"Connection error: {e.reason}") from None


def activate_with_api_key(
    api_key: str,
    api_url: str = "https://api.tinkclaw.com",
    device_name: Optional[str] = None,
    timeout: int = 15,
) -> dict:
    """Register this device directly using an API key.

    Alternative to token flow — user enters their API key directly.

    Returns:
        {"device_id": "...", "auth_token": "...", "config": {...}}
    """
    if not device_name:
        device_name = f"{platform.node() or 'CLI'} ({platform.system()})"

    body = {
        "device_name": device_name,
        "device_type": _detect_type(),
        "os": platform.platform(),
    }

    req = urllib.request.Request(
        f"{api_url.rstrip('/')}/api/mesh/register",
        data=json.dumps(body).encode(),
        headers={
            "Content-Type": "application/json",
            "Authorization": f"Bearer {api_key}",
        },
        method="POST",
    )

    try:
        with urllib.request.urlopen(req, timeout=timeout) as resp:
            return json.loads(resp.read())
    except urllib.error.HTTPError as e:
        raw = e.read().decode()
        try:
            err = json.loads(raw)
        except (json.JSONDecodeError, ValueError):
            err = {"error": raw}
        raise RuntimeError(
            f"Registration failed ({e.code}): {err.get('error', raw)}"
        ) from None
    except urllib.error.URLError as e:
        raise RuntimeError(f"Connection error: {e.reason}") from None


def _detect_type() -> str:
    system = platform.system().lower()
    machine = platform.machine().lower()
    if "arm" in machine or "aarch" in machine:
        return "sbc"  # Raspberry Pi, etc.
    if system == "darwin":
        return "desktop"
    if system == "linux":
        return "server"
    if system == "windows":
        return "desktop"
    return "unknown"
