from mitmproxy import http
from pathlib import Path
import re

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

def response(flow: http.HTTPFlow):
    if flow.request.pretty_host == "www.google.com" and flow.request.path.startswith("/search"):
        print("[KYNG-STEP] 1 RESPONSE MASUK", flush=True)
    if not flow.response:
        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 flow.request.pretty_host == "www.google.com" and flow.request.path.startswith("/search"):
            print("[KYNG-STEP] 2 HTML DAPAT LEN=", len(html or ""), flush=True)

        if not html:
            return

        lower = html.lower()
        marker = "</head>"
        pos = lower.find(marker)

        if pos < 0:
            return

        js = JS_FILE.read_text(encoding="utf-8")
        if flow.request.pretty_host == "www.google.com" and flow.request.path.startswith("/search"):
            print("[KYNG-STEP] 3 JS DAPAT LEN=", len(js), flush=True)

        nonce_match = re.search(r'<script[^>]+nonce=["\\\']([^"\\\']+)["\\\']', html, re.I)
        nonce = nonce_match.group(1) if nonce_match else None
        if flow.request.pretty_host == "www.google.com" and flow.request.path.startswith("/search"):
            print("[KYNG-STEP] 4 NONCE=", bool(nonce), flush=True)

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

        html = html[:pos] + injection + html[pos:]
        if flow.request.pretty_host == "www.google.com" and flow.request.path.startswith("/search"):
            print("[KYNG-STEP] 5 INJECTION MASUK LEN=", len(html), flush=True)

        flow.response.set_text(html)
        if flow.request.pretty_host == "www.google.com" and flow.request.path.startswith("/search"):
            print("[KYNG-STEP] 6 SET_TEXT BERHASIL", flush=True)

        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] CHARLES-STYLE INJECTED:", flow.request.pretty_url)

    except Exception as e:
        print("[KYNG] INJECT ERROR:", repr(e))

def request(flow):
    if "google.com" in flow.request.pretty_host:
        print("[KYNG-DEBUG] GOOGLE REQUEST:", flow.request.pretty_url, flush=True)

def responseheaders(flow):
    if flow.request.pretty_host == "www.google.com" and flow.request.path.startswith("/search"):
        print(
            "[KYNG-RESP] STATUS=",
            flow.response.status_code,
            "TYPE=",
            flow.response.headers.get("content-type", "NONE"),
            "ENC=",
            flow.response.headers.get("content-encoding", "NONE"),
            flush=True
        )
