#!/usr/bin/env python3
"""Run this on the second device to take the next available name in turn."""

import json
import socket
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen


API_URL = "https://mostafatools.com/api.php"


def read_response(response) -> dict:
    raw = response.read().decode("utf-8", errors="replace")
    try:
        return json.loads(raw)
    except json.JSONDecodeError:
        return {
            "error": "الموقع أعاد استجابة غير صالحة؛ تأكد من رفع api.php الصحيح.",
            "http_status": getattr(response, "status", getattr(response, "code", "unknown")),
        }


def send(body: dict, token: str) -> tuple[int, dict]:
    request = Request(
        API_URL,
        data=json.dumps(body).encode("utf-8"),
        headers={"Content-Type": "application/json", "X-API-Token": token},
        method="POST",
    )
    try:
        with urlopen(request, timeout=20) as response:
            return response.status, read_response(response)
    except HTTPError as error:
        return error.code, read_response(error)


token = 'mostafacheetos010101010'
try:
    status, result = send(
        {"action": "take_next", "device": socket.gethostname()}, token
    )
    print(json.dumps(result, ensure_ascii=False, indent=2))
except URLError as error:
    print(f"تعذر الاتصال بالموقع: {error}")
    raise SystemExit(2)

raise SystemExit(0 if status == 200 else 1)
