"""Local TLS policy simulation. No network connection or Supabase access.

Requires Python 3 with ssl and the openssl command for a temporary certificate.
Uses a modern client restricted to two different cipher lists, not old devices.
"""
import json
import ssl
import subprocess
import tempfile
from pathlib import Path


def simulate():
    results = []
    with tempfile.TemporaryDirectory(prefix="supabase-tls-memory-") as directory:
        cert = Path(directory) / "cert.pem"
        key = Path(directory) / "key.pem"
        subprocess.run(
            ["openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
             "-days", "1", "-subj", "/CN=localhost", "-keyout", str(key),
             "-out", str(cert)],
            check=True, capture_output=True, timeout=20,
        )
        for suite in ("ECDHE-RSA-AES128-GCM-SHA256", "ECDHE-RSA-AES128-SHA256"):
            server_context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
            server_context.load_cert_chain(cert, key)
            client_context = ssl.create_default_context(cafile=str(cert))
            for context in (server_context, client_context):
                context.minimum_version = ssl.TLSVersion.TLSv1_2
                context.maximum_version = ssl.TLSVersion.TLSv1_2
            server_context.set_ciphers("ECDHE-RSA-AES128-GCM-SHA256")
            client_context.set_ciphers(suite)
            client_in, client_out, server_in, server_out = [ssl.MemoryBIO() for _ in range(4)]
            client = client_context.wrap_bio(client_in, client_out, server_hostname="localhost")
            server = server_context.wrap_bio(server_in, server_out, server_side=True)
            completed = [False, False]
            error = None
            for _ in range(30):
                for index, connection in enumerate((client, server)):
                    if completed[index]:
                        continue
                    try:
                        connection.do_handshake()
                        completed[index] = True
                    except ssl.SSLWantReadError:
                        pass
                    except ssl.SSLError as exception:
                        error = {"side": ("client", "server")[index], "message": str(exception)}
                        break
                if error:
                    break
                for source, target in ((client_out, server_in), (server_out, client_in)):
                    data = source.read()
                    if data:
                        target.write(data)
                if all(completed):
                    break
            if not all(completed) and error is None:
                raise RuntimeError("Handshake did not complete within the simulation limit")
            results.append({
                "offeredCipher": suite,
                "handshakeSucceeded": all(completed),
                "negotiatedProtocol": client.version() if all(completed) else None,
                "negotiatedCipher": client.cipher()[0] if all(completed) else None,
                "error": error,
            })
    if not results[0]["handshakeSucceeded"] or results[1]["handshakeSucceeded"]:
        raise RuntimeError("Unexpected simulation outcome")
    return {
        "type": "local-in-memory-tls-simulation",
        "runtime": ssl.OPENSSL_VERSION,
        "serverPolicy": "TLS 1.2; ECDHE-RSA-AES128-GCM-SHA256 only",
        "scope": "No network or Supabase access. Forced cipher lists on one client, not legacy hardware tests.",
        "results": results,
    }


if __name__ == "__main__":
    print(json.dumps(simulate(), ensure_ascii=False, indent=2))
