"""奇门云签名直连客户端。业务数据由官方平台直接返回客户服务器。"""
import argparse
import json
import mimetypes
import re
import secrets
from pathlib import Path
from urllib import error, parse, request

ROOT = Path(__file__).resolve().parent
ORIGIN = "https://api.miandanni.com"
ENDPOINTS = {
    "qimen": "/api/gateway/sign",
    "wanxiang": "/api/wanxiang/sign",
    "taobao": "/api/taobao/sign",
}


QIMEN_TARGETS = {
    ("a1q40taq0j.api.taobao.com", "/router/qm"),
    ("hu3cgwt0tc.api.taobao.com", "/router/qm"),
    ("3ldsmu02o9.api.taobao.com", "/router/qm"),
    ("4edcetl6p0.api.taobao.com", "/router/qm"),
    ("qimen.api.taobao.com", "/router/qmtest"),
}
# Verified local official web catalog; only these exact PHP paths are accepted.
WDT_WEB_STANDARD_METHODS = set([
    "aftersale_stockin_confirm.php",
    "aftersales_refund_create.php",
    "aftersales_refund_sourceless_create.php",
    "api_goods_stock_change_ack.php",
    "api_goods_stock_change_query.php",
    "api_goodsspec_push.php",
    "api_trade_live_extend_query.php",
    "cfg_tags_query.php",
    "employee_query.php",
    "goods_brand_query.php",
    "goods_category_flat_query.php",
    "goods_category_query.php",
    "goods_push.php",
    "goods_query.php",
    "his_trade_query.php",
    "jit_delivery_order_query.php",
    "logistics.php",
    "logistics_multi_query.php",
    "logistics_sync_ack.php",
    "logistics_sync_query.php",
    "operational_order_create.php",
    "operational_order_query.php",
    "operational_stock_detail_query.php",
    "order_audit.php",
    "order_cancel.php",
    "order_reject.php",
    "order_stop_waiting.php",
    "pdk_basic_spu_create.php",
    "pdk_basic_spu_detail_query.php",
    "pdk_basic_spu_query.php",
    "pick_order_query.php",
    "pick_status_ack.php",
    "pick_trade_query.php",
    "provider_goods_query.php",
    "purchase_apply_query.php",
    "purchase_order_push.php",
    "purchase_order_query.php",
    "purchase_provider_create.php",
    "purchase_provider_query.php",
    "purchase_return_order_push.php",
    "purchase_return_query.php",
    "refund_query.php",
    "sales_refund_push.php",
    "sales_trade_batch_change.php",
    "sales_trade_batch_remark_flag.php",
    "sales_trade_modify.php",
    "sales_trade_replenish.php",
    "sales_trade_simple_change.php",
    "sales_trade_tags_modify.php",
    "shop.php",
    "spec_barcode_push.php",
    "stock_detail_report_query.php",
    "stock_full_query.php",
    "stock_goods_sn_query.php",
    "stock_inout_sn_query.php",
    "stock_outsource_order_query.php",
    "stock_production_order_query.php",
    "stock_query.php",
    "stock_query_detail.php",
    "stock_sync_by_pd.php",
    "stock_transfer_create.php",
    "stock_transfer_query.php",
    "stockin_order_push.php",
    "stockin_order_query.php",
    "stockin_order_query_refund.php",
    "stockout_order_push.php",
    "stockout_order_query.php",
    "stockout_order_query_trade.php",
    "stockout_order_query_trade_cancel.php",
    "suites_push.php",
    "suites_query.php",
    "trade_push.php",
    "trade_query.php",
    "unique_code_print.php",
    "unique_code_query.php",
    "unique_code_status_change.php",
    "vip_api_goods_query.php",
    "vip_api_refund_query.php",
    "vip_api_trade_query.php",
    "vip_stockout_sales_weight_push.php",
    "vip_wms_stockinout_order_push.php",
    "warehouse_query.php",
    "xsd_self_delivery_location_callback.php",
    "xsd_upload_media.php"
])

class NoRedirect(request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        return None


class CallError(RuntimeError):
    """保留 HTTP 状态和原始错误响应；不包含请求 URL 或签名凭据。"""
    def __init__(self, phase, status, payload):
        super().__init__(phase + " HTTP " + str(status))
        self.phase, self.status, self.payload = phase, status, payload


def check_result(payload):
    pending = [payload]
    while pending:
        obj = pending.pop()
        if not isinstance(obj, dict):
            continue
        if obj.get("ok") is False or "error_response" in obj or obj.get("success") is False:
            raise RuntimeError("平台返回失败，请查看响应中的错误码、说明和请求号")
        if str(obj.get("error_count", "0")) not in ("0", "None"):
            raise RuntimeError("存在逐项失败，请检查 error_details")
        for field in ("code", "errorcode", "error_code"):
            if obj.get(field) not in (None, "", 0, "0"):
                raise RuntimeError("平台返回业务错误，请查看原始响应")
        for key, value in obj.items():
            if key in ("response", "result", "data", "top_result", "info") or key.endswith("_response") or key.endswith("_top_part_data"):
                if isinstance(value, str):
                    try:
                        value = json.loads(value)
                    except ValueError:
                        continue
                pending.append(value)


class Client:
    def __init__(self, config, timeout=100, opener=None):
        self.config = config
        if config.get("mode", "direct") != "direct":
            raise ValueError("此客户端仅支持 direct 签名直连，请重新生成 AI 对接包")
        self.timeout = timeout
        self.opener = opener or request.build_opener(NoRedirect())
        self._private_values = {config["apiKey"]}

    def display(self, payload):
        text = json.dumps(payload, ensure_ascii=False, indent=2)
        for value in sorted(self._private_values, key=len, reverse=True):
            if value:
                text = text.replace(value, "[REDACTED]")
        return text

    def _post(self, url, body, headers, phase):
        req = request.Request(url, data=body, method="POST", headers=headers)
        try:
            with self.opener.open(req, timeout=self.timeout) as response:
                raw = response.read()
        except error.HTTPError as exc:
            raw = exc.read()
            try:
                payload = json.loads(raw)
            except ValueError:
                payload = {"message": raw.decode("utf-8", errors="replace")}
            raise CallError(phase, exc.code, payload) from None
        except (error.URLError, TimeoutError, OSError):
            raise RuntimeError("网络失败或超时；未自动重试、未切换网关。写操作结果可能未知，请先查询实际状态。") from None
        try:
            return json.loads(raw)
        except ValueError:
            raise RuntimeError("响应不是 JSON；未自动重试，请核实实际执行状态。") from None

    def _endpoint(self, service):
        if service not in ENDPOINTS or service not in self.config["services"]:
            raise ValueError("该服务未配置")
        path = ENDPOINTS[service]
        url = self.config["services"][service].get("signEndpoint", ORIGIN + path)
        if url != ORIGIN + path:
            raise ValueError("奇门云接口地址无效")
        return url

    def _validate_plan(self, plan, service, method):
        if plan.get("version") != 1 or plan.get("service") != service or plan.get("method") != method or not isinstance(plan.get("ticketId"), str):
            raise ValueError("签名响应与本次请求不匹配")
        signed = plan.get("request", {})
        url = parse.urlsplit(signed.get("url", ""))
        if url.scheme != "https" or url.username or url.password or url.fragment or url.port not in (None, 443):
            raise ValueError("签名目标必须是官方 HTTPS 地址")
        if service == "qimen":
            allowed = (url.hostname, url.path) in QIMEN_TARGETS or (url.hostname == "openapi.huice.com" and url.path in {"/openapi/" + name for name in WDT_WEB_STANDARD_METHODS})
        else:
            allowed = url.hostname in ("eco.taobao.com", "gw.api.taobao.com") and url.path == "/router/rest"
        if not allowed or signed.get("httpMethod") != "POST":
            raise ValueError("签名响应包含非官方目标")
        headers = signed.get("headers", {})
        if not isinstance(headers, dict) or any(str(k).lower() not in ("accept", "content-type") or not isinstance(v, str) or "\r" in v or "\n" in v for k, v in headers.items()):
            raise ValueError("签名响应包含不允许的请求头")
        if self.config["apiKey"] in json.dumps(signed, ensure_ascii=False):
            raise ValueError("客户密钥不得发送到上游平台")
        fields = signed.get("fields", {})
        if not isinstance(fields, dict):
            raise ValueError("签名文本字段无效")
        for key, value in fields.items():
            if key.lower() in ("session", "access_token", "sign", "wdt_salt", "wdt_sign") and isinstance(value, str):
                self._private_values.add(value)
        if service == "qimen" and isinstance(signed.get("body"), str):
            for key, value in parse.parse_qsl(signed["body"]):
                if key.lower() in ("session", "access_token", "sign", "wdt_salt", "wdt_sign"):
                    self._private_values.add(value)
        for key, value in parse.parse_qsl(url.query):
            if key.lower() in ("session", "access_token", "sign", "wdt_salt", "wdt_sign"):
                self._private_values.add(value)
        return signed

    @staticmethod
    def _multipart(fields, file_fields, files):
        boundary = "qimenyun-" + secrets.token_hex(16)
        chunks = []
        def append(headers, data):
            chunks.extend([("--" + boundary + "\r\n" + headers + "\r\n\r\n").encode("utf-8"), data, b"\r\n"])
        for name, value in fields.items():
            if not re.fullmatch(r"[A-Za-z0-9_]+", name) or not isinstance(value, str):
                raise ValueError("签名文本字段无效")
            append('Content-Disposition: form-data; name="' + name + '"', value.encode("utf-8"))
        declared = {item["name"]: item for item in file_fields}
        if set(files) - set(declared) or any(item.get("required") and name not in files for name, item in declared.items()):
            raise ValueError("本地文件与官方文件字段不匹配")
        for name, path in files.items():
            if not re.fullmatch(r"[A-Za-z0-9_]+", name):
                raise ValueError("文件字段名无效")
            path = Path(path)
            filename = declared[name].get("filename") or path.name
            if filename != path.name or any(c in filename for c in '\r\n"\\/'):
                raise ValueError("文件名与签名申请不匹配")
            mime = "image/bmp" if path.suffix.lower() == ".bmp" else mimetypes.guess_type(filename)[0] or "application/octet-stream"
            append('Content-Disposition: form-data; name="' + name + '"; filename="' + filename + '"\r\nContent-Type: ' + mime, path.read_bytes())
        chunks.append(("--" + boundary + "--\r\n").encode("ascii"))
        return b"".join(chunks), "multipart/form-data; boundary=" + boundary

    def call(self, service, body, files=None):
        """执行一次明确的业务请求；无自动重试。files={官方字段名: 本地路径}。"""
        files = files or {}
        payload = dict(body)
        if "files" in payload:
            raise ValueError("文件请通过 call(..., files={字段名:本地路径}) 提供")
        headers = {"Content-Type": "application/json", "Authorization": "Bearer " + self.config["apiKey"]}
        if files:
            payload["files"] = {name: {"filename": Path(path).name} for name, path in files.items()}
        envelope = self._post(self._endpoint(service), json.dumps(payload, ensure_ascii=False).encode("utf-8"), headers, "签名")
        if envelope.get("ok") is not True or not isinstance(envelope.get("data"), dict):
            raise CallError("签名", 200, envelope)
        signed = self._validate_plan(envelope["data"], service, body["method"])
        encoding = signed.get("encoding")
        upstream_headers = dict(signed.get("headers", {}))
        if encoding in ("raw", "form") and service == "qimen" and isinstance(signed.get("body"), str) and not files:
            # 正文参与奇门签名，必须原样发送，不解析或重新序列化。
            data = signed["body"].encode("utf-8")
        elif encoding == "form" and service != "qimen" and not files:
            fields = signed.get("fields", {})
            if not isinstance(fields, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in fields.items()):
                raise ValueError("签名字段必须是字符串")
            data = parse.urlencode(fields).encode("utf-8")
            upstream_headers["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8"
        elif encoding == "multipart" and service == "taobao":
            data, content_type = self._multipart(signed.get("fields", {}), signed.get("fileFields", []), files)
            upstream_headers = {k: v for k, v in upstream_headers.items() if k.lower() != "content-type"}
            upstream_headers["Content-Type"] = content_type
        else:
            raise ValueError("签名响应编码与请求不匹配")
        # 新建请求头；客户 Bearer 密钥绝不转发到官方平台。
        return self._post(signed["url"], data, upstream_headers, "平台")


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("request_file", nargs="?")
    parser.add_argument("--config", default=str(ROOT / "config.json"))
    parser.add_argument("--order-id")
    args = parser.parse_args()
    config = json.loads(Path(args.config).read_text(encoding="utf-8"))
    if not args.request_file:
        print("请选择请求文件（未发送网络请求）：")
        for path in sorted((Path(args.config).resolve().parent / "requests").glob("*.json")):
            print("  python client.py requests/" + path.name)
        return
    example = json.loads(Path(args.request_file).read_text(encoding="utf-8"))
    service, body = example["service"], example["body"]
    allowed = {"taobao.shopcats.list.get", "taobao.universalbp.new.account.get.can.use.bizcode", "wdt.trade.query", "wdt.sales.tradequery.querywithdetail", "jushuitan.order.list.query"}
    if body["method"] not in allowed:
        raise SystemExit("命令行演示只执行只读验证；写操作请按官方文档调用 Client.call 并确认具体业务。")
    if service == "qimen":
        if not args.order_id:
            raise SystemExit("请添加 --order-id 真实订单号；尚未发送请求")
        def fill(value):
            if isinstance(value, dict):
                return {key: fill(item) for key, item in value.items()}
            if isinstance(value, list):
                return [fill(item) for item in value]
            return args.order_id if value == "__ORDER_ID__" else value
        body["params"] = fill(body["params"])
    client = Client(config)
    try:
        payload = client.call(service, body)
        print(client.display(payload))
        check_result(payload)
    except CallError as exc:
        print(client.display(exc.payload))
        raise SystemExit(str(exc)) from None
    except (RuntimeError, ValueError) as exc:
        raise SystemExit(str(exc)) from None


if __name__ == "__main__":
    main()
