#!/usr/bin/env python3
"""Isolated oEmbed origin for the WordPress full-chain reproduction.

The provider address is supplied by the runtime harness so each clean run can use
an isolated Docker subnet. It returns only valid, bounded iframe HTML.
"""

from __future__ import annotations

import json
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit

HOST = os.environ.get("PRUVA_OEMBED_HOST", "11.77.0.2")
PORT = int(os.environ.get("PRUVA_OEMBED_PORT", "8080"))
TARGET = f"http://{HOST}:{PORT}/target"
OEMBED = f"http://{HOST}:{PORT}/oembed"


class Handler(BaseHTTPRequestHandler):
    def do_GET(self) -> None:
        path = urlsplit(self.path).path
        if path == "/target":
            body = (
                "<!doctype html><html><head>"
                f'<link rel="alternate" type="application/json+oembed" href="{OEMBED}">'
                "</head><body>source-derived oEmbed target</body></html>"
            ).encode()
            content_type = "text/html; charset=utf-8"
            status = 200
        elif path == "/oembed":
            body = json.dumps(
                {
                    "version": "1.0",
                    "type": "rich",
                    "provider_name": "Pruva isolated lab",
                    "provider_url": TARGET,
                    "title": "Pruva transition hook",
                    "width": 1,
                    "height": 1,
                    "html": f'<iframe src="http://{HOST}:{PORT}/frame"></iframe>',
                }
            ).encode()
            content_type = "application/json"
            status = 200
        else:
            body = b"not found"
            content_type = "text/plain"
            status = 404

        self.send_response(status)
        self.send_header("Content-Type", content_type)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, fmt: str, *args: object) -> None:
        print(f"provider_http {self.address_string()} {fmt % args}", flush=True)


if __name__ == "__main__":
    print(f"provider_listening={HOST}:{PORT}", flush=True)
    ThreadingHTTPServer(("0.0.0.0", PORT), Handler).serve_forever()
