#!/usr/bin/env python3
"""Minimal HTTP server for the StylingAgent.getStyles cross-origin POC.

Serves attacker.html and victim.html from the current directory.
The Host header is irrelevant (Chrome's --host-resolver-rules maps both
a.example.com and b.example.com to 127.0.0.1); only the path matters.
"""
import http.server
import os
import socketserver

PORT = int(os.environ.get('POC_PORT', '8080'))
HERE = os.path.dirname(os.path.abspath(__file__))


class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):  # noqa: N802
        name = self.path.lstrip('/').split('?')[0] or 'attacker.html'
        path = os.path.join(HERE, name)
        if not os.path.isfile(path):
            self.send_error(404)
            return
        with open(path, 'rb') as f:
            body = f.read().replace(b':PORT/', f':{PORT}/'.encode())
        self.send_response(200)
        self.send_header('Content-Type', 'text/html; charset=utf-8')
        self.send_header('Content-Length', str(len(body)))
        # Explicitly opt OUT of origin-keyed agent clustering so the
        # same-site cross-origin iframe stays in the parent's process.
        self.send_header('Origin-Agent-Cluster', '?0')
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, fmt, *args):
        pass


if __name__ == '__main__':
    socketserver.TCPServer.allow_reuse_address = True
    with socketserver.TCPServer(('127.0.0.1', PORT), Handler) as httpd:
        print(f'serving on http://127.0.0.1:{PORT}/', flush=True)
        httpd.serve_forever()
