import json
from mitmproxy import http

TARGET_PREFIX = "http://150.109.18.253"
NEW_AUTH_CODE = "VIP30-3716475E"
NEW_USER_IDENTIFIER = "4bd05b4b67404d961b89ccdf2cc093e73506697dcf80f6ccb7cb0e671505308e"


def request(flow: http.HTTPFlow) -> None:
    req = flow.request

    # 只处理 POST 请求
    if req.method.upper() != "POST":
        return

    # 只处理指定前缀的 URL
    if not req.pretty_url.startswith(TARGET_PREFIX):
        return

    # 优先过滤 JSON 请求
    content_type = (req.headers.get("Content-Type") or "").lower()
    if "application/json" not in content_type:
        return

    # 解析 JSON body
    try:
        body_text = req.get_text()
        data = json.loads(body_text) if body_text else {}
    except Exception:
        return

    if not isinstance(data, dict):
        return

    # 只要 body 中同时含有 auth_code 和 user_identifier 就修改
    if "auth_code" in data and "user_identifier" in data:
        data["auth_code"] = NEW_AUTH_CODE
        data["user_identifier"] = NEW_USER_IDENTIFIER

        # 回写 JSON 到请求体
        new_body = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
        req.set_text(new_body)


# mitmdump -s stop.py --mode upstream:http://127.0.0.1:7890
