#!/usr/bin/env python3
from http import HTTPStatus
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.error import HTTPError, URLError
from urllib.parse import urlsplit
from urllib.request import HTTPCookieProcessor, Request, build_opener
import html


REMOTE_ORIGIN = "https://1xaud.em7bd7.co"

opener = build_opener(HTTPCookieProcessor())


MODULE_CONFIGS = {
    "partnership": [
        ("partnershipIframe", "/embed/partnership/partnership.asp", "setPartnershipIframeHeight", 0, 600),
    ],
    "game-rtp": [
        ("gameRtpIframe", "/embed/game-rtp/game-rtp.asp", "setGameRtpIframeHeight", 50, 900),
    ],
    "domain-status": [
        ("domainstatusIframe", "/embed/domain-status/domain-status.asp", "setDomainStatusIframeHeight", 0, 700),
    ],
}


WRAPPER_TEMPLATE = """<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>__TITLE__</title>
  <style>
    html,
    body {
      margin: 0;
      background: #0f1218;
      font-family: Arial, sans-serif;
    }

    .frame-wrap {
      position: relative;
      max-width: 1000px;
      margin: 0 auto 28px;
      overflow: hidden;
      border: none;
      background: #151921;
    }

    .frame-wrap iframe {
      display: block;
      width: 100%;
      overflow: hidden;
      border: none;
    }
  </style>
  <script>
    window._ = {
      getVar(name) {
        return name === "merchantId" ? "1888" : "";
      }
    };
  </script>
</head>
<body>
__IFRAMES__

  <script>
    (() => {
      const merchantId = (typeof _ !== "undefined" && typeof _.getVar === "function") ? (_.getVar("merchantId") ?? "") : "";
      if (!merchantId) {
        console.log("merchantId not found");
        return;
      }

      function init(id, heightMessageType, extraHeight) {
        const iframe = document.getElementById(id);
        if (!iframe) {
          console.log(id + " not found");
          return;
        }
        iframe.addEventListener("load", function() {
          iframe.contentWindow.postMessage({ type: "setIframeData", clientMerchant: merchantId }, "*");
        });
        window.addEventListener("message", function(event) {
          if (event.data && event.data.type === heightMessageType) {
            iframe.style.height = event.data.height + extraHeight + "px";
          }
        }, false);
      }

__INIT_CALLS__
    })();
  </script>
</body>
</html>
"""


def build_wrapper(selected):
    modules = []
    for key in selected:
        modules.extend(MODULE_CONFIGS[key])

    iframe_html = "\n".join(
        f'  <div class="frame-wrap">\n'
        f'    <iframe id="{iframe_id}" src="{src}" style="min-height: {min_height}px"></iframe>\n'
        f'  </div>'
        for iframe_id, src, _message_type, _extra_height, min_height in modules
    )
    init_calls = "\n".join(
        f'      init("{iframe_id}", "{message_type}", {extra_height});'
        for iframe_id, _src, message_type, extra_height, _min_height in modules
    )
    title = "1XAUD proxied iframe render"
    return (
        WRAPPER_TEMPLATE
        .replace("__TITLE__", title)
        .replace("__IFRAMES__", iframe_html)
        .replace("__INIT_CALLS__", init_calls)
    )


class ProxyHandler(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def do_GET(self):
        path = urlsplit(self.path).path
        if path in {"/", "/render-1888-proxy.html", "/render-1888-all.html"}:
            body = build_wrapper(["partnership", "game-rtp", "domain-status"]).encode("utf-8")
            self.send_bytes(body, "text/html; charset=utf-8")
            return
        if path == "/render-1888-partnership.html":
            body = build_wrapper(["partnership"]).encode("utf-8")
            self.send_bytes(body, "text/html; charset=utf-8")
            return
        if path == "/render-1888-game-rtp.html":
            body = build_wrapper(["game-rtp"]).encode("utf-8")
            self.send_bytes(body, "text/html; charset=utf-8")
            return
        if path == "/render-1888-domain-status.html":
            body = build_wrapper(["domain-status"]).encode("utf-8")
            self.send_bytes(body, "text/html; charset=utf-8")
            return
        self.proxy()

    def do_POST(self):
        self.proxy()

    def send_bytes(self, body, content_type, status=HTTPStatus.OK):
        self.send_response(status)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(body)))
        self.send_header("Cache-Control", "no-store")
        self.end_headers()
        self.wfile.write(body)

    def proxy(self):
        parsed = urlsplit(self.path)
        target = REMOTE_ORIGIN + parsed.path
        if parsed.query:
            target += "?" + parsed.query

        body = None
        if self.command == "POST":
            length = int(self.headers.get("Content-Length", "0") or 0)
            body = self.rfile.read(length) if length else b""

        headers = {
            "User-Agent": self.headers.get(
                "User-Agent",
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0 Safari/537.36",
            ),
            "Referer": REMOTE_ORIGIN + "/embed/partnership/partnership.asp",
            "Origin": REMOTE_ORIGIN,
        }
        if "Content-Type" in self.headers:
            headers["Content-Type"] = self.headers["Content-Type"]

        request = Request(target, data=body, headers=headers, method=self.command)
        try:
            with opener.open(request, timeout=30) as response:
                response_body = response.read()
                self.send_response(response.status)
                for key, value in response.headers.items():
                    lower = key.lower()
                    if lower in {
                        "content-length",
                        "connection",
                        "transfer-encoding",
                        "content-encoding",
                        "x-frame-options",
                        "content-security-policy",
                        "report-to",
                        "nel",
                        "alt-svc",
                    }:
                        continue
                    self.send_header(key, value)
                self.send_header("Content-Length", str(len(response_body)))
                self.send_header("Cache-Control", "no-store")
                self.end_headers()
                self.wfile.write(response_body)
        except HTTPError as exc:
            response_body = exc.read()
            self.send_response(exc.code)
            self.send_header("Content-Type", exc.headers.get("Content-Type", "text/plain"))
            self.send_header("Content-Length", str(len(response_body)))
            self.end_headers()
            self.wfile.write(response_body)
        except URLError as exc:
            body = f"Proxy error: {html.escape(str(exc.reason))}".encode("utf-8")
            self.send_bytes(body, "text/plain; charset=utf-8", HTTPStatus.BAD_GATEWAY)

    def log_message(self, format, *args):
        print("%s - - [%s] %s" % (self.client_address[0], self.log_date_time_string(), format % args))


if __name__ == "__main__":
    server = ThreadingHTTPServer(("localhost", 8898), ProxyHandler)
    print("Proxy server listening on http://localhost:8898/render-1888-proxy.html")
    server.serve_forever()
