#!/usr/bin/env python3
"""雲管家 合作夥伴 API v1 — Python 快速開始（只用標準函式庫，Python 3.9+）

用法：
    export CM_API_KEY=cmp_test_xxxxxxxx           # 先用沙盒金鑰
    python3 quickstart.py demo                    # 跑一輪：ping → 列設備 → 啟動 → 追結果
    python3 quickstart.py member                  # 會員餘額：用手機查 → 用會員編號再查（沙盒手機 0900000001）
    python3 quickstart.py member --phone 0912345678
    python3 quickstart.py webhook --port 8000     # 起一個 webhook 接收端（驗簽示範）
    CM_WEBHOOK_SECRET=whsec_xxx python3 quickstart.py webhook

重點（照著做就不會重複投幣）：
    1. 每個「意圖」產生一把 Idempotency-Key，重試一律沿用同一把，絕對不要換新的。
    2. POST 回 202 只代表受理：accepted＝雲端已受理、sent＝已送到設備端，要追到 succeeded／failed／expired。
       沒有設備回報就不會 succeeded；confirmable=false 的指令最多到 sent。
    3. 沒收到回應時，先用同一把 key 查 GET /commands?idempotency_key=…，查不到再用同一把 key 重送。

會員餘額（v1.4，金鑰要有 member:read）：
    4. 只能用手機查一位會員；回 member_id（mem_ 開頭、固定不變，存起來之後用它查）、遮罩手機、各群組餘額。
    5. 儲值金是「每個店家群組各一份」：balances[] 每筆附 store_ids；total_balance 是授權範圍內的加總。
    6. 推播 member.balance_changed 以 data.balance（變動後餘額）為準，不要自己累加 delta（事件不保證順序）。
"""
import argparse
import hashlib
import hmac
import json
import os
import sys
import time
import uuid
import urllib.error
import urllib.parse
import urllib.request
from http.server import BaseHTTPRequestHandler, HTTPServer

BASE = os.environ.get("CM_BASE_URL", "https://laundry-api.cloudmonster.tw/api/partner/v1")
API_KEY = os.environ.get("CM_API_KEY", "")
RETRY_DELAYS = [2, 5, 10, 30]          # 5xx／網路錯誤的退避秒數（文件「通用規則」）
TERMINAL = {"succeeded", "failed", "expired"}


class ApiError(Exception):
    def __init__(self, status, body):
        self.status, self.body = status, body
        super().__init__(f"HTTP {status}: {body.get('code')} {body.get('message')} (request_id={body.get('request_id')})")


def request(method, path, body=None, headers=None, timeout=15):
    """送一個請求；429 照 Retry-After 等，5xx／網路錯誤照退避重試。POST 重試時 headers 不變（同一把 Idempotency-Key）。"""
    data = json.dumps(body).encode() if body is not None else None
    h = {"Authorization": f"Bearer {API_KEY}", "Accept": "application/json"}
    if data is not None:
        h["Content-Type"] = "application/json"
    h.update(headers or {})
    for attempt in range(len(RETRY_DELAYS) + 1):
        req = urllib.request.Request(BASE + path, data=data, method=method, headers=h)
        try:
            with urllib.request.urlopen(req, timeout=timeout) as r:
                raw = r.read()
                return r.status, (json.loads(raw) if raw else None)
        except urllib.error.HTTPError as e:
            payload = json.loads(e.read() or b"{}")
            if e.code == 429:
                wait = int(e.headers.get("Retry-After", "5"))
                print(f"  429 限流，{wait} 秒後重試")
                time.sleep(wait)
                continue
            if e.code >= 500 and attempt < len(RETRY_DELAYS):
                time.sleep(RETRY_DELAYS[attempt])
                continue
            raise ApiError(e.code, payload)
        except (urllib.error.URLError, TimeoutError) as e:
            if attempt < len(RETRY_DELAYS):
                print(f"  網路錯誤（{e}），{RETRY_DELAYS[attempt]} 秒後用同一把 key 重試")
                time.sleep(RETRY_DELAYS[attempt])
                continue
            raise
    raise RuntimeError("重試次數用完")


def send_command(device_id, action, params=None, reference=None):
    """下指令。回指令物件（status 可能還不是終態）。"""
    idem = str(uuid.uuid4())   # 這一個意圖的 key —— 下面所有重試都用它
    body = {"action": action, "params": params or {}}
    if reference:
        body["reference"] = reference
    try:
        _, cmd = request("POST", f"/devices/{device_id}/commands", body, {"Idempotency-Key": idem})
        return cmd
    except (urllib.error.URLError, TimeoutError, RuntimeError):
        # 結果不明：先查雲端有沒有收到，再決定要不要（用同一把 key）重送
        try:
            _, cmd = request("GET", f"/commands?idempotency_key={idem}")
            return cmd
        except ApiError as e:
            if e.status == 404:
                _, cmd = request("POST", f"/devices/{device_id}/commands", body, {"Idempotency-Key": idem})
                return cmd
            raise


def wait_command(command_id, timeout_sec=150):
    """輪詢到終態。confirmable=false 的指令最多到 sent，這裡就直接回。"""
    deadline = time.time() + timeout_sec
    while True:
        _, cmd = request("GET", f"/commands/{command_id}")
        print(f"  指令 {command_id}：{cmd['status']}")
        if cmd["status"] in TERMINAL or (cmd["status"] == "sent" and not cmd["confirmable"]):
            return cmd
        if time.time() > deadline:
            return cmd
        time.sleep(3)


def demo():
    if not API_KEY:
        sys.exit("請先 export CM_API_KEY=cmp_test_…")
    _, me = request("GET", "/ping")
    print(f"金鑰：{me['partner_name']}（{me['environment']}），權限 {me['scopes']}，門市 {me['store_ids']}")
    store = me["store_ids"][0]
    _, data = request("GET", f"/stores/{store}/devices")
    for d in data["devices"]:
        print(f"  {d['id']:<14} {d['name']:<12} {d['state']:<11} 剩 {d['remain_sec']:>5}s  可用 {d['capabilities']}")
    target = next((d for d in data["devices"] if "start" in d["capabilities"] and d["state"] == "idle"), None)
    if not target:
        print("沒有可以遠端啟動的待機設備")
        return
    ref = f"DEMO-{int(time.time())}"
    # start 只照面板目前選定的洗程啟動、不投幣 → 要換洗程先 switch_program，要投幣先 add_coins
    program = target["programs"][0] if target["programs"] else None
    if program and "switch_program" in target["capabilities"]:
        print(f"切洗程 → {program['name']}（{program['id']}）")
        wait_command(send_command(target["id"], "switch_program", {"program_id": program["id"]}, reference=ref + "-P")["command_id"])
    if program and program.get("price") and "add_coins" in target["capabilities"]:
        coins = -(-program["price"] // (target.get("coin_value") or 10))   # 無條件進位
        print(f"投幣 {coins} 枚")
        wait_command(send_command(target["id"], "add_coins", {"coins": coins}, reference=ref + "-C")["command_id"])
    print(f"啟動 {target['id']}")
    result = wait_command(send_command(target["id"], "start", reference=ref)["command_id"])
    print(f"結果：{result['status']}"
          + (f"（依據 {result['confirmed_by']}）" if result.get("confirmed_by") else "")
          + (f"（{result['error']['code']}：{result['error']['message']}）" if result.get("error") else ""))


def member(phone):
    if not API_KEY:
        sys.exit("請先 export CM_API_KEY=cmp_test_…")
    _, me = request("GET", "/ping")
    if "member:read" not in me["scopes"]:
        sys.exit(f"這把金鑰沒有 member:read 權限（目前 {me['scopes']}）→ 請業主在 App 申請時勾「查會員餘額」")
    try:
        _, data = request("GET", f"/members?phone={urllib.parse.quote(phone)}")
    except ApiError as e:
        if e.status == 400:
            sys.exit(f"手機格式不對（要 09 開頭 10 碼）：{e}")
        raise
    if not data["members"]:
        print(f"{phone}：查無會員（或這位會員在你授權的門市沒有儲值錢包）")
        return
    m = data["members"][0]
    print(f"會員 {m['member_id']}（{m['phone_masked']}）合計 {m['total_balance']} {m['currency']}")
    for b in m["balances"]:
        print(f"  門市 {', '.join(b['store_ids'])}：{b['balance']}")
    # member_id 固定不變：存在你們的系統裡，之後直接用它查，不必再帶手機
    _, again = request("GET", f"/members/{m['member_id']}")
    print(f"用會員編號再查一次：合計 {again['total_balance']}（{'一致' if again['total_balance'] == m['total_balance'] else '不一致'}）")


def verify_signature(secret, header, raw_body, tolerance=300, now=None):
    """驗 X-CM-Signature。raw_body 必須是收到的原始位元組，不要先 json 解析再序列化。"""
    parts = [p.split("=", 1) for p in header.split(",") if "=" in p]
    ts = next((v for k, v in parts if k == "t"), None)
    if ts is None or not ts.isdigit() or abs((now or time.time()) - int(ts)) > tolerance:
        return False
    expected = hmac.new(secret.encode(), f"{ts}.".encode() + raw_body, hashlib.sha256).hexdigest()
    return any(hmac.compare_digest(v, expected) for k, v in parts if k == "v1")


def webhook_server(port):
    secret = os.environ.get("CM_WEBHOOK_SECRET", "")
    seen = set()

    class Handler(BaseHTTPRequestHandler):
        def do_POST(self):
            raw = self.rfile.read(int(self.headers.get("Content-Length", 0)))
            if not secret or not verify_signature(secret, self.headers.get("X-CM-Signature", ""), raw):
                self.send_response(401); self.end_headers(); return
            event = json.loads(raw)
            self.send_response(200); self.end_headers()   # 先回 200（5 秒內），再慢慢處理
            if event["event_id"] in seen:                 # 重送時 event_id 不變 → 去重
                return
            seen.add(event["event_id"])
            d = event["data"]
            if event["type"] == "member.balance_changed":
                # 以 balance（變動後餘額）覆蓋你們存的值；delta 只拿來顯示
                print(f"[{event['occurred_at']}] 會員 {d['member_id']}（{d['phone_masked']}）門市 {','.join(d['store_ids'])}："
                      f"{d['previous_balance']} → {d['balance']}（{d['delta']:+d}，{d['reason']}）")
                return
            print(f"[{event['occurred_at']}] {event['type']} {event.get('device_id') or ''} {json.dumps(d, ensure_ascii=False)}")

        def log_message(self, *args):
            pass

    print(f"webhook 接收端在 :{port}（{'已設' if secret else '⚠️ 沒設'} CM_WEBHOOK_SECRET）")
    HTTPServer(("0.0.0.0", port), Handler).serve_forever()


if __name__ == "__main__":
    ap = argparse.ArgumentParser(description="雲管家合作夥伴 API 快速開始")
    sub = ap.add_subparsers(dest="cmd", required=True)
    sub.add_parser("demo")
    mp = sub.add_parser("member")
    mp.add_argument("--phone", default="0900000001", help="會員手機（沙盒預設 0900000001）")
    w = sub.add_parser("webhook")
    w.add_argument("--port", type=int, default=8000)
    args = ap.parse_args()
    if args.cmd == "demo":
        demo()
    elif args.cmd == "member":
        member(args.phone)
    else:
        webhook_server(args.port)
