from mitmproxy import http
from pathlib import Path
import re

JS_FILE = Path("/opt/kyng/kyng.js")

def response(flow: http.HTTPFlow):
    if not flow.response:
        return

    # PENTING: hanya Google
    if flow.request.pretty_host != "www.google.com":
        return

    content_type = flow.response.headers.get("content-type", "").lower()
    if "text/html" not in content_type:
        return

    try:
        html = flow.response.get_text(strict=False)
        if not html:
            return

        print("[KYNG] GOOGLE HTML:", flow.request.path[:100], flush=True)

        js = JS_FILE.read_text(encoding="utf-8")

        # Cari nonce milik script Google kalau tersedia
        m = re.search(
            r'<script[^>]+nonce=["\']([^"\']+)["\']',
            html,
            re.I
        )
        nonce = m.group(1) if m else None

        if nonce:
            payload = '\n<script nonce="' + nonce + '">\n' + js + '\n</script>\n'
            print("[KYNG] NONCE FOUND", flush=True)
        else:
            payload = "\n<script>\n" + js + "\n</script>\n"
            print("[KYNG] NONCE NOT FOUND", flush=True)

        # Sama konsepnya dengan Charles: masukkan sebelum </head>
        pos = html.lower().find("</head>")
        if pos < 0:
            print("[KYNG] NO HEAD", flush=True)
            return

        html = html[:pos] + payload + html[pos:]

        # Set response dulu
        flow.response.set_text(html)

        # Hapus CSP seperti rule Charles
        flow.response.headers.pop("content-security-policy", None)
        flow.response.headers.pop("content-security-policy-report-only", None)
        flow.response.headers.pop("content-length", None)

        print("[KYNG] GOOGLE INJECT SUCCESS", flush=True)

    except Exception as e:
        print("[KYNG] ERROR:", repr(e), flush=True)
