"""Diagnose connection issues with the Sibilance server."""

from __future__ import annotations

import asyncio
import platform
import socket
import ssl
import sys


SERVER = "https://sibilance.fly.dev"
HOST = "sibilance.fly.dev"


def main() -> None:
    print(f"Python {sys.version}")
    print(f"Platform: {platform.platform()}")
    print(f"SSL: {ssl.OPENSSL_VERSION}")
    print()

    # DNS resolution
    print(f"[1] DNS resolution for {HOST}")
    try:
        results = socket.getaddrinfo(HOST, 443, type=socket.SOCK_STREAM)
        for family, _type, _proto, _canon, addr in results:
            label = "IPv6" if family == socket.AF_INET6 else "IPv4"
            print(f"    {label}: {addr[0]}")
    except Exception as e:
        print(f"    FAILED: {e}")
        return

    # Raw socket connect (IPv4 only)
    print()
    print("[2] TCP connect (IPv4)")
    try:
        ipv4 = [
            addr[0]
            for fam, _, _, _, addr in results
            if fam == socket.AF_INET
        ]
        if ipv4:
            s = socket.create_connection((ipv4[0], 443), timeout=10)
            print(f"    OK — connected to {ipv4[0]}:443")
            s.close()
        else:
            print("    No IPv4 addresses found")
    except Exception as e:
        print(f"    FAILED: {e}")

    # SSL handshake
    print()
    print("[3] TLS handshake (stdlib)")
    try:
        ctx = ssl.create_default_context()
        with socket.create_connection((HOST, 443), timeout=10) as sock:
            with ctx.wrap_socket(sock, server_hostname=HOST) as ssock:
                print(f"    OK — {ssock.version()}, cert CN: {ssock.getpeercert()['subject'][0][0][1]}")
    except Exception as e:
        print(f"    FAILED: {e}")

    # httpx without truststore
    print()
    print("[4] httpx GET /health (certifi certs)")
    try:
        import httpx
        print(f"    httpx {httpx.__version__}")
        r = asyncio.run(_httpx_get(verify=True))
        print(f"    OK — {r.status_code}")
    except Exception as e:
        print(f"    FAILED: {type(e).__name__}: {e}")

    # httpx with truststore
    print()
    print("[5] httpx GET /health (truststore / OS certs)")
    try:
        import truststore
        ctx = truststore.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
        print(f"    truststore {truststore.__version__}")
        r = asyncio.run(_httpx_get(verify=ctx))
        print(f"    OK — {r.status_code}")
    except ImportError:
        print("    SKIPPED — truststore not installed")
    except Exception as e:
        print(f"    FAILED: {type(e).__name__}: {e}")

    # httpx with verify=False (bypass TLS)
    print()
    print("[6] httpx GET /health (verify=False, TLS bypass)")
    try:
        r = asyncio.run(_httpx_get(verify=False))
        print(f"    OK — {r.status_code}")
    except Exception as e:
        print(f"    FAILED: {type(e).__name__}: {e}")

    # ApiClient test
    print()
    print("[7] ApiClient.create_device_code()")
    try:
        from sibilance.api.client import ApiClient
        api = ApiClient(SERVER)
        dc = asyncio.run(_test_device_code(api))
        print(f"    OK — code: {dc.code}")
    except Exception as e:
        print(f"    FAILED: {type(e).__name__}: {e}")

    print()
    print("Done.")


async def _httpx_get(verify: object = True) -> "httpx.Response":
    import httpx
    async with httpx.AsyncClient(timeout=10.0, verify=verify) as client:  # type: ignore[arg-type]
        return await client.get(f"{SERVER}/health")


async def _test_device_code(api: object) -> object:
    from sibilance.api.client import ApiClient
    assert isinstance(api, ApiClient)
    try:
        return await api.create_device_code()
    finally:
        await api.close()


if __name__ == "__main__":
    main()
