"""CLI entry point for sorcgcs-server."""

import argparse
import builtins
import os
import signal
import sys

_builtin_print = builtins.print
def print(*args, **kwargs):
    kwargs.setdefault("flush", True)
    _builtin_print(*args, **kwargs)

from . import __version__


def main():
    # Force unbuffered output so prints appear immediately in all terminals
    os.environ["PYTHONUNBUFFERED"] = "1"
    sys.stdout.reconfigure(line_buffering=True) if hasattr(sys.stdout, 'reconfigure') else None
    parser = argparse.ArgumentParser(
        prog="sorcgcs-server",
        description="SorcGCS Local Server — game preview, file management, AI agent support, and CorridorKey GPU server",
    )
    parser.add_argument("--port", type=int, default=8080, help="Port (default: 8080)")
    parser.add_argument("--host", type=str, default="0.0.0.0", help="Host (default: 0.0.0.0)")
    parser.add_argument("--dir", type=str, default=None, help="Games directory (default: cwd)")
    parser.add_argument("--no-corridorkey", action="store_true", help="Skip CorridorKey GPU server")
    parser.add_argument("--version", action="version", version=f"sorcgcs-server {__version__}")
    args = parser.parse_args()

    print("")
    print("  ================================================")
    print(f"   SORCGCS SERVER v{__version__}")
    print("  ================================================")

    ck_proc = None
    ck_info = {"status": "skipped", "gpu": None, "error": None}

    if not args.no_corridorkey:
        from .corridorkey import launch_corridorkey
        ck_info = launch_corridorkey()
        ck_proc = ck_info.get("proc")
    else:
        print("  CorridorKey: skipped (--no-corridorkey)")

    # Print final status dashboard
    _print_dashboard(args, ck_info)

    def cleanup(*_):
        print("")
        if ck_proc and ck_proc.poll() is None:
            print("  Stopping CorridorKey server...")
            ck_proc.terminate()
            try:
                ck_proc.wait(timeout=5)
            except Exception:
                ck_proc.kill()
        print("  All servers stopped.")
        sys.exit(0)

    signal.signal(signal.SIGINT, cleanup)
    signal.signal(signal.SIGTERM, cleanup)

    from .server import run_server

    try:
        run_server(port=args.port, host=args.host, games_dir=args.dir)
    except KeyboardInterrupt:
        cleanup()


def _print_dashboard(args, ck_info):
    import os
    games_dir = os.path.abspath(args.dir) if args.dir else os.getcwd()

    print("")
    print("  ------------------------------------------------")
    print("   STATUS")
    print("  ------------------------------------------------")
    print(f"   File Server:   http://localhost:{args.port}  [OK]")

    ck_status = ck_info.get("status", "skipped")
    if ck_status == "running":
        gpu = ck_info.get("gpu", "unknown")
        print(f"   CorridorKey:   http://localhost:8100  [OK]  GPU: {gpu}")
    elif ck_status == "skipped":
        print("   CorridorKey:   skipped")
    elif ck_status == "setup_failed":
        print("   CorridorKey:   [FAILED] setup error")
        err = ck_info.get("error", "")
        if err:
            for line in err.split("\n")[:3]:
                print(f"                  {line}")
    elif ck_status == "crashed":
        print("   CorridorKey:   [FAILED] process crashed")
        err = ck_info.get("error", "")
        if err:
            for line in err.split("\n")[:5]:
                print(f"                  {line}")
    elif ck_status == "timeout":
        print("   CorridorKey:   [WARNING] started but not healthy")
        err = ck_info.get("error", "")
        if err:
            print(f"                  {err}")
    else:
        print(f"   CorridorKey:   [{ck_status}]")

    print("  ------------------------------------------------")
    print(f"   Games folder:  {games_dir}")
    print("  ------------------------------------------------")
    print("")
    print("  Press Ctrl+C to stop all servers.")
    print("")


if __name__ == "__main__":
    main()
