import hashlib
import hmac
import json
import os
import time
import urllib.error
import urllib.parse
import urllib.request


def required(name):
    value = os.environ.get(name, "")
    if not value:
        raise RuntimeError(f"Set {name}")
    return value


def signature(params, path, secret):
    message = path + "".join(
        key + params[key] for key in sorted(params)
        if key != "sign" and params[key] != ""
    )
    return hmac.new(secret.encode(), message.encode(), hashlib.sha256).hexdigest().upper()


def call(endpoint, path, business):
    params = {
        "app_key": required("ALIEXPRESS_APP_KEY"),
        "sign_method": "sha256",
        "timestamp": str(time.time_ns() // 1_000_000),
        **business,
    }
    params["sign"] = signature(params, path, required("ALIEXPRESS_APP_SECRET"))
    body = urllib.parse.urlencode(params).encode()
    request = urllib.request.Request(endpoint, data=body, headers={
        "Content-Type": "application/x-www-form-urlencoded;charset=utf-8",
    })
    try:
        with urllib.request.urlopen(request, timeout=20) as response:
            data = json.load(response)
    except urllib.error.HTTPError as error:
        raise RuntimeError(f"AliExpress HTTP {error.code}; response omitted") from None
    except (urllib.error.URLError, TimeoutError):
        raise RuntimeError("AliExpress connection failed; details omitted") from None
    if not isinstance(data, dict):
        raise RuntimeError("Unexpected AliExpress response")
    if "error_response" in data:
        # Error messages can echo request values. Keep the raw body private.
        raise RuntimeError("AliExpress rejected the request; inspect securely")
    return data


def sync(method, params):
    return call("https://api-sg.aliexpress.com/sync", "", {
        "method": method,
        "session": required("ALIEXPRESS_ACCESS_TOKEN"),
        **params,
    })


def save_private(filename, data):
    # Create without overwriting an existing file. Run with umask 077 as well.
    with open(filename, "x", encoding="utf-8", opener=lambda p, f: os.open(p, f, 0o600)) as file:
        json.dump(data, file, indent=2)
        file.write("\n")
