"""
mitmproxy addon: on outbound Lumo generation requests, relabel the encrypted
system message as a user message. Plaintext JSON only — the encrypted content
and request_key are left byte-identical, so the client's own crypto still works.

Run:  mitmdump -s lumo_roleflip.py
(or) mitmweb -s lumo_roleflip.py   # adds a UI to watch the flip happen
"""
import re
from mitmproxy import http

TARGET_HOST = "lumo.proton.me"
TARGET_PATH = "/api/ai/v1/chat/completions"

# Tolerant of optional whitespace the real client may emit: "role": "system"
_SYS = re.compile(rb'("role"\s*:\s*)"system"')


def request(flow: http.HTTPFlow) -> None:
    if flow.request.pretty_host != TARGET_HOST:
        return
    if not flow.request.path.startswith(TARGET_PATH):
        return
    if flow.request.method != "POST":
        return

    body = flow.request.raw_content or b""
    new, n = _SYS.subn(rb'\1"user"', body)
    if n:
        flow.request.raw_content = new
        # keep Content-Length correct (same length here, but be safe)
        flow.request.headers["content-length"] = str(len(new))
        ctx_log(f"[roleflip] system→user on {flow.request.path}  ({n} replaced)")


def ctx_log(msg: str) -> None:
    try:
        from mitmproxy import ctx
        ctx.log.info(msg)
    except Exception:
        print(msg)
