#!/usr/bin/env python3
"""Integration test for operator, operator_proxy, and cvd_host_orchestrator."""

import functools
import http.server
import json
import os
import pathlib
import socket
import ssl
import subprocess
import sys
import tempfile
import threading
import time
import urllib.error
import urllib.request


def get_free_port():
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.bind(("127.0.0.1", 0))
        return s.getsockname()[1]


def http_request(url, method="GET", data=None, headers=None, insecure=False):
    ctx = None
    if insecure:
        ctx = ssl.create_default_context()
        ctx.check_hostname = False
        ctx.verify_mode = ssl.CERT_NONE
    req = urllib.request.Request(url, data=data, headers=headers or {}, method=method)
    with urllib.request.urlopen(req, timeout=10, context=ctx) as resp:
        return resp.status, resp.read()


def wait_for_http(url, insecure=False, timeout=15.0):
    deadline = time.monotonic() + timeout
    last_err = None
    while time.monotonic() < deadline:
        try:
            status, body = http_request(url, insecure=insecure)
            if status == 200:
                return body
        except Exception as exc:
            last_err = exc
        time.sleep(0.2)
    raise RuntimeError(f"Timed out waiting for {url}: {last_err}")


def wait_for_path(path, timeout=15.0):
    deadline = time.monotonic() + timeout
    while time.monotonic() < deadline:
        if os.path.exists(path):
            return
        time.sleep(0.1)
    raise RuntimeError(f"Timed out waiting for path {path}")


def main():
    tmp_root = os.environ.get("AUTOPKGTEST_TMP") or tempfile.mkdtemp(prefix="cf-op-")
    tmp = pathlib.Path(tmp_root)
    cert_dir = tmp / "cert"
    cert_dir.mkdir(parents=True, exist_ok=True)
    artifacts_dir = tmp / "artifacts"
    artifacts_dir.mkdir(parents=True, exist_ok=True)
    cf_dir = tmp / "cf"
    (cf_dir / "instances" / "cvd-1" / "logs").mkdir(parents=True, exist_ok=True)
    cf_config = cf_dir / "cuttlefish_config.json"
    cf_config.write_text(
        json.dumps({"root_dir": str(cf_dir), "instances": {"1": {"run_as_daemon": False}}})
    )
    proxy_env = os.environ.copy()
    proxy_env["CUTTLEFISH_CONFIG_FILE"] = str(cf_config)
    proxy_env["CUTTLEFISH_INSTANCE"] = "1"

    print("=== Generating ephemeral self-signed TLS certificate ===")
    subprocess.run(
        [
            "openssl", "req",
            "-newkey", "rsa:2048",
            "-x509", "-sha256", "-days", "1", "-nodes",
            "-out", str(cert_dir / "cert.pem"),
            "-keyout", str(cert_dir / "key.pem"),
            "-subj", "/CN=localhost",
        ],
        check=True,
    )

    op_http_port = get_free_port()
    op_https_port = get_free_port()
    proxy_port = get_free_port()
    ho_port = get_free_port()
    dev_http_port = get_free_port()
    dev_sock_path = str(tmp / "operator.sock")
    ctrl_sock_path = str(tmp / "operator_control.sock")

    # Serve cuttlefish-base WebRTC assets from an in-process mock device HTTP server.
    handler_cls = functools.partial(
        http.server.SimpleHTTPRequestHandler,
        directory="/usr/lib/cuttlefish-common/usr/share/webrtc/assets",
    )
    mock_http = http.server.ThreadingHTTPServer(("127.0.0.1", dev_http_port), handler_cls)
    mock_http_thread = threading.Thread(target=mock_http.serve_forever, daemon=True)
    mock_http_thread.start()

    procs = []
    dev_sock = None
    try:
        print(f"=== Starting operator (http={op_http_port}, https={op_https_port}) ===")
        procs.append(
            subprocess.Popen(
                [
                    "/usr/lib/cuttlefish-common/bin/operator",
                    f"--listen_addr=127.0.0.1",
                    f"--http_port={op_http_port}",
                    f"--https_port={op_https_port}",
                    f"--tls_cert_dir={cert_dir}",
                    f"--socket_path={dev_sock_path}",
                    f"--control_socket_path={ctrl_sock_path}",
                ],
                cwd="/usr/share/cuttlefish-common/operator",
            )
        )

        print(f"=== Starting operator_proxy ({proxy_port} -> {op_https_port}) ===")
        procs.append(
            subprocess.Popen(
                [
                    "/usr/lib/cuttlefish-common/bin/operator_proxy",
                    f"--server_port={proxy_port}",
                    f"--operator_port={op_https_port}",
                ],
                env=proxy_env,
            )
        )

        print(f"=== Starting cvd_host_orchestrator (http={ho_port} -> op={op_http_port}) ===")
        procs.append(
            subprocess.Popen(
                [
                    "/usr/bin/cvd_host_orchestrator",
                    "-listen_addr=127.0.0.1",
                    f"-http_port={ho_port}",
                    f"-operator_http_port={op_http_port}",
                    f"-cvd_artifacts_dir={artifacts_dir}",
                ]
            )
        )

        wait_for_path(dev_sock_path)
        infra_raw = wait_for_http(f"http://127.0.0.1:{op_http_port}/infra_config")
        infra = json.loads(infra_raw)
        assert "ice_servers" in infra, f"Unexpected infra_config: {infra}"
        print("OK: operator /infra_config")

        print("=== Verifying WebUI static and dh-linktree assets ===")
        for rel in (
            "/",
            "/index.html",
            "/main.js",
            "/polyfills.js",
            "/indigo-pink.css",
            "/css/material-design-icons-no-codepoints.css",
            "/css/fonts/MaterialIcons-Regular.woff2",
        ):
            status, body = http_request(f"http://127.0.0.1:{op_http_port}{rel}")
            assert status == 200 and len(body) > 0, f"Failed static asset {rel}"
            if rel in ("/", "/index.html"):
                assert b"<app-root>" in body, f"<app-root> missing in {rel}"
        print("OK: WebUI static & font assets")

        print("=== Verifying operator_proxy HTTPS forwarding ===")
        proxied_index = wait_for_http(f"https://127.0.0.1:{proxy_port}/", insecure=True)
        assert b"<app-root>" in proxied_index, "operator_proxy did not serve WebUI index.html"
        print("OK: operator_proxy HTTPS")

        print("=== Verifying cvd_host_orchestrator routes and operator proxy ===")
        ops = json.loads(wait_for_http(f"http://127.0.0.1:{ho_port}/operations"))
        assert isinstance(ops, dict) and "operations" in ops, f"Unexpected /operations reply: {ops}"
        ho_infra = json.loads(wait_for_http(f"http://127.0.0.1:{ho_port}/infra_config"))
        assert "ice_servers" in ho_infra, f"host_orchestrator failed to proxy /infra_config: {ho_infra}"
        print("OK: cvd_host_orchestrator")

        print("=== Registering mock device over Unix SOCK_SEQPACKET ===")
        dev_sock = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET)
        dev_sock.settimeout(10.0)
        dev_sock.connect(dev_sock_path)
        dev_sock.send(
            json.dumps(
                {
                    "device_id": "cvd-test-1",
                    "device_port": dev_http_port,
                    "device_info": {"adb_serial": "0.0.0.0:6520"},
                }
            ).encode()
        )
        cfg_reply = json.loads(dev_sock.recv(65536))
        assert cfg_reply.get("message_type") == "config", f"Unexpected device config reply: {cfg_reply}"

        devices = json.loads(http_request(f"http://127.0.0.1:{op_http_port}/devices")[1])
        assert any(d.get("device_id") == "cvd-test-1" for d in devices), f"Device not listed: {devices}"

        dev_info = json.loads(http_request(f"http://127.0.0.1:{op_http_port}/devices/cvd-test-1")[1])
        assert dev_info["device_id"] == "cvd-test-1"
        assert dev_info["registration_info"]["adb_serial"] == "0.0.0.0:6520"
        print("OK: device registration and /devices API")

        print("=== Verifying intercepted server_connector.js and proxied WebRTC assets ===")
        _, intercepted = http_request(
            f"http://127.0.0.1:{op_http_port}/devices/cvd-test-1/files/js/server_connector.js"
        )
        expected_intercept = pathlib.Path(
            "/usr/share/cuttlefish-common/operator/intercept/js/server_connector.js"
        ).read_bytes()
        assert intercepted == expected_intercept, "server_connector.js was not intercepted properly"

        _, client_html = http_request(
            f"http://127.0.0.1:{op_http_port}/devices/cvd-test-1/files/client.html"
        )
        assert b"js/jquery.min.js" in client_html
        _, jquery_js = http_request(
            f"http://127.0.0.1:{op_http_port}/devices/cvd-test-1/files/js/jquery.min.js"
        )
        assert len(jquery_js) > 1000
        print("OK: intercept and device file reverse-proxy")

        print("=== Verifying bidirectional signaling via /polled_connections ===")
        _, conn_raw = http_request(
            f"http://127.0.0.1:{op_http_port}/polled_connections",
            method="POST",
            data=json.dumps({"device_id": "cvd-test-1"}).encode(),
            headers={"Content-Type": "application/json"},
        )
        conn_id = json.loads(conn_raw)["connection_id"]
        http_request(
            f"http://127.0.0.1:{op_http_port}/polled_connections/{conn_id}/:forward",
            method="POST",
            data=json.dumps({"payload": {"ping": "cuttlefish"}}).encode(),
            headers={"Content-Type": "application/json"},
        )
        forwarded = json.loads(dev_sock.recv(65536))
        assert forwarded["message_type"] == "client_msg"
        assert forwarded["payload"] == {"ping": "cuttlefish"}

        dev_sock.send(
            json.dumps(
                {
                    "client_id": forwarded["client_id"],
                    "payload": {"pong": "verified"},
                }
            ).encode()
        )
        msgs = []
        deadline = time.monotonic() + 5.0
        while time.monotonic() < deadline:
            msgs = json.loads(
                http_request(f"http://127.0.0.1:{op_http_port}/polled_connections/{conn_id}/messages")[1]
            ) or []
            if any(
                m.get("message_type") == "device_msg" and m.get("payload") == {"pong": "verified"}
                for m in msgs
            ):
                break
            time.sleep(0.1)
        assert any(
            m.get("message_type") == "device_msg" and m.get("payload") == {"pong": "verified"}
            for m in msgs
        ), f"Expected echoed device_msg, got: {msgs}"
        print("OK: bidirectional signaling")

        dev_sock.close()
        dev_sock = None
        deadline = time.monotonic() + 5.0
        while time.monotonic() < deadline:
            devices = json.loads(http_request(f"http://127.0.0.1:{op_http_port}/devices")[1]) or []
            if not any(d.get("device_id") == "cvd-test-1" for d in devices):
                break
            time.sleep(0.1)
        assert not any(d.get("device_id") == "cvd-test-1" for d in devices), "Device did not unregister"
        print("=== test-operator passed successfully! ===")
    finally:
        if dev_sock is not None:
            dev_sock.close()
        mock_http.shutdown()
        for p in procs:
            p.terminate()
        for p in procs:
            try:
                p.wait(timeout=5)
            except subprocess.TimeoutExpired:
                p.kill()


if __name__ == "__main__":
    main()
