from __future__ import annotations
import os
import socket
import uvicorn





def find_free_port(host: str = "127.0.0.1", start: int = 8000, max_tries: int = 200) -> int:
    """
    Find a free TCP port by probing sequentially.
    If 8000 is occupied, try 8001, 8002, ...
    """
    for port in range(start, start + max_tries):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
            # connect_ex returns 0 if something is listening
            if s.connect_ex((host, port)) != 0:
                return port
    raise RuntimeError(f"No free port found in range {start}..{start + max_tries - 1}")


def main() -> None:
    host = "127.0.0.1"
    port = find_free_port(host=host, start=8000, max_tries=200)
    url = f"http://{host}:{port}/"

    # Pass URL to the FastAPI app so it opens the browser only AFTER startup is complete
    os.environ["ECDALLM_URL"] = url

    print(f"ecdallm running at {url} (Ctrl+C to stop)")

    uvicorn.run(
        "ecdallm.app.main:app",
        host=host,
        port=port,
        reload=False,
        log_level="info",
    )
