import hashlib
import hmac
import json
import os
import secrets
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from pathlib import Path

base = os.environ["API_BASE"].rstrip("/")
app_id = os.environ["APP_ID"]
secret = os.environ["MERCHANT_SECRET"]
method = sys.argv[1] if len(sys.argv) > 1 else "GET"
path = sys.argv[2] if len(sys.argv) > 2 else "/v1/merchant"
base_url = urllib.parse.urlsplit(base)
if base_url.scheme != "https" or not base_url.hostname or base_url.username or base_url.query or base_url.fragment or base_url.path:
    raise ValueError("API_BASE must be an HTTPS origin")
route = path.split("?", 1)[0]
if method not in ("GET", "POST") or route not in ("/v1/merchant", "/v1/account/balance", "/v1/payment-orders") or "#" in path:
    raise ValueError("Unsupported API method or path")
if method == "POST" and path != "/v1/payment-orders":
    raise ValueError("POST is only supported for /v1/payment-orders")
# URL-encode query values before building path. Sign the complete raw path,
# including the '?' and query string; never include the API domain.
body = Path(sys.argv[3]).read_bytes().decode("utf-8") if method == "POST" else ""
timestamp = str(int(time.time()))
nonce = secrets.token_hex(16)
canonical = "\n".join([method, path, app_id, timestamp, nonce, body, ""])
signature = hmac.new(
    secret.encode("utf-8"), canonical.encode("utf-8"), hashlib.sha256
).hexdigest()
request = urllib.request.Request(base + path, method=method,
    data=body.encode("utf-8") if method == "POST" else None,
    headers={
        "Content-Type": "application/json; charset=utf-8",
        "X-App-Id": app_id, "X-Timestamp": timestamp,
        "X-Nonce": nonce, "X-Signature": signature,
    })

class NoRedirect(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None

try:
    with urllib.request.build_opener(NoRedirect).open(request, timeout=10) as response:
        result = json.loads(response.read().decode("utf-8"))
except urllib.error.HTTPError as error:
    raise SystemExit("Unexpected HTTP status: " + str(error.code))
if not isinstance(result, dict) or type(result.get("code")) is not int:
    raise ValueError("Invalid API response")
print(json.dumps(result, ensure_ascii=False))
if result["code"] != 0:
    sys.exit(1)
# On create timeout, query third_order_no before deciding whether to retry.
# Repeated creation always returns 1019; it does not return the existing order.
