"""Dump request URL + response body for flows matching a filter substring."""
import sys, json
from mitmproxy import io as miio
from mitmproxy.exceptions import FlowReadException

flow_file = sys.argv[1]
filter_substr = sys.argv[2]
max_dumps = int(sys.argv[3]) if len(sys.argv) > 3 else 1

dumps = 0
with open(flow_file, "rb") as f:
    reader = miio.FlowReader(f)
    try:
        for flow in reader.stream():
            if not hasattr(flow, "request"):
                continue
            url = flow.request.pretty_url
            if filter_substr not in url:
                continue
            if not flow.response:
                continue
            dumps += 1
            print(f"\n=== {flow.request.method} {url} ===")
            print(f"Status: {flow.response.status_code}")
            print(f"Content-Type: {flow.response.headers.get('Content-Type', '?')}")
            print("--- response (first 4000 chars) ---")
            try:
                body = flow.response.get_text(strict=False)
                if body:
                    try:
                        parsed = json.loads(body)
                        body = json.dumps(parsed, indent=2, ensure_ascii=False)
                    except (json.JSONDecodeError, ValueError):
                        pass
                    print(body[:4000])
                else:
                    print("(binary or empty)")
            except Exception as e:
                print(f"[error decoding body: {e}]")
            if dumps >= max_dumps:
                break
    except FlowReadException as e:
        print(f"[warn] flow truncated: {e}", file=sys.stderr)
