#!/usr/bin/env python3
"""
HTTPS server for the FLEDGE NaN priority_vector POC.

Serves the POC page, bidding/scoring worklet scripts, and ad creative
over HTTPS with a self-signed certificate. FLEDGE requires HTTPS origins
for interest-group owners, sellers, and worklet scripts.
"""
import http.server
import os
import ssl
import subprocess
import sys

HOST = "0.0.0.0"
PORT = 8443

ROOT = os.path.dirname(os.path.abspath(__file__))
CERT = os.path.join(ROOT, "server.pem")


def ensure_cert():
    if os.path.exists(CERT):
        return
    # Generate a self-signed cert valid for a.test (resolved via
    # --host-resolver-rules in the run.sh wrapper). Use a wildcard SAN so
    # multiple test subdomains work if needed.
    subprocess.check_call([
        "openssl", "req", "-x509", "-newkey", "rsa:2048",
        "-keyout", CERT, "-out", CERT,
        "-days", "30", "-nodes",
        "-subj", "/CN=a.test",
        "-addext",
        "subjectAltName=DNS:a.test,DNS:*.test,DNS:localhost,IP:127.0.0.1",
    ])


class Handler(http.server.SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=ROOT, **kwargs)

    def end_headers(self):
        path = self.path.split("?", 1)[0]
        # Worklet scripts must opt in via this response header.
        if path.endswith(".js"):
            self.send_header("Ad-Auction-Allowed", "true")
            self.send_header("X-Allow-FLEDGE", "true")
        # Allow embedding the ad creative.
        if path.endswith("ad.html"):
            self.send_header("Supports-Loading-Mode", "fenced-frame")
        self.send_header("Cache-Control", "no-store")
        super().end_headers()

    def guess_type(self, path):
        if path.endswith(".js"):
            return "application/javascript"
        return super().guess_type(path)


def main():
    ensure_cert()
    httpd = http.server.ThreadingHTTPServer((HOST, PORT), Handler)
    ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    ctx.load_cert_chain(CERT)
    httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
    sys.stderr.write(f"Serving HTTPS on https://a.test:{PORT}/poc.html\n")
    httpd.serve_forever()


if __name__ == "__main__":
    main()
