# gsm_mitm.py - addon cho mitmproxy, chay tren PC (10.0.7.1)
# Tuong duong voi mitm/gsm_rewrite.js nhung cho luong traffic du dien thoai dan ve PC.
#
# Chay:
#   mitmdump --listen-host 0.0.0.0 --listen-port 8080 -s gsm_mitm.py
#   (hoac: mitmproxy ... de co giao dien console, mitmweb ... de xem web UI port 8081)
#
# Logic: chi sua response item key="driver_force_update" danh cho iOS:
#   forceUpdate=false, minVersion=0  (566 la build number; 3.17 = 550 < 566 nen bi doi update)

import json
from mitmproxy import http, ctx

TARGET_KEY = "driver_force_update"


def as_value(v):
    if isinstance(v, str):
        try:
            return json.loads(v)
        except Exception:
            return None
    return v


def patch_item(item):
    if not isinstance(item, dict) or item.get("key") != TARGET_KEY:
        return False
    os_list = item.get("os")
    for_ios = not os_list or (isinstance(os_list, list) and (len(os_list) == 0 or "ios" in os_list))
    if not for_ios:
        return False

    changed = False
    val = as_value(item.get("value"))
    if isinstance(val, dict):
        if "forceUpdate" in val:
            val["forceUpdate"] = False
            changed = True
        if "minVersion" in val:
            val["minVersion"] = 0
            changed = True
        if "min_version" in val:
            val["min_version"] = 0
            changed = True
        item["value"] = json.dumps(val, ensure_ascii=False) if isinstance(item.get("value"), str) else val
    return changed


def rewrite_flow_json(data):
    n = 0
    if isinstance(data, list):
        for it in data:
            if patch_item(it):
                n += 1
    elif isinstance(data, dict) and isinstance(data.get("data"), list):
        for it in data["data"]:
            if patch_item(it):
                n += 1
    return n


def response(flow: http.HTTPFlow):
    # bat moi request co path chua remote_config (host co the la hostname hoac IP thuan
    # khi app resolve DNS rieng va ket noi bang IP — mitmproxy van bam duoc)
    if "remote_config" not in flow.request.path:
        return

    host = flow.request.host

    try:
        data = json.loads(flow.response.get_text())
    except Exception as e:
        ctx.log.warn(f"[gsm] khong parse duoc JSON tu {host}{flow.request.path}: {e}")
        return

    n = rewrite_flow_json(data)
    if n:
        flow.response.set_text(json.dumps(data, ensure_ascii=False))
        ctx.log.info(f"[gsm] DA SUA {n} item driver_force_update (host={host}) -> forceUpdate=false, minVersion=0")
    else:
        # log de theo doi neu GSM them config moi
        keys = []
        if isinstance(data, list):
            keys = [str(it.get("key")) for it in data if isinstance(it, dict)]
        elif isinstance(data, dict) and isinstance(data.get("data"), list):
            keys = [str(it.get("key")) for it in data["data"] if isinstance(it, dict)]
        if any("force" in k.lower() or "update" in k.lower() for k in keys):
            ctx.log.warn(f"[gsm] co key lien quan update nhua khong patch: {keys} — xem lai logic!")


def request(flow: http.HTTPFlow):
    # log request lan dau de kiem tra luong traffic da di qua PC
    if "remote_config" in flow.request.path and not getattr(flow, "_gsm_logged", False):
        flow._gsm_logged = True
        ctx.log.info(f"[gsm] request: {flow.request.pretty_url}")
