"""CLI for onit-workspace: start/stop the Workspace MCP Server."""

import argparse
import os
import signal
import subprocess
import sys
import time

STATE_DIR = os.path.expanduser("~/.onit-workspace")
PID_FILE = os.path.join(STATE_DIR, "pid")
LOG_FILE = os.path.join(STATE_DIR, "server.log")


def _ensure_state_dir():
    os.makedirs(STATE_DIR, mode=0o700, exist_ok=True)


def _read_pid():
    if not os.path.exists(PID_FILE):
        return None
    with open(PID_FILE) as f:
        try:
            return int(f.read().strip())
        except (ValueError, OSError):
            return None


def _is_running(pid):
    try:
        os.kill(pid, 0)
        return True
    except (OSError, ProcessLookupError):
        return False


def _start(args):
    if args.foreground:
        _run_server(args)
        return

    pid = _read_pid()
    if pid and _is_running(pid):
        print(f"Server is already running (PID {pid})")
        print(f"  SSE endpoint: http://{args.host}:{args.port}/sse")
        return

    _ensure_state_dir()

    # Build command to run the server in a subprocess
    cmd = [
        sys.executable, "-m", "onit_workspace.cli",
        "start", "--foreground",
        "--host", args.host,
        "--port", str(args.port),
    ]
    if args.credentials_file:
        cmd.extend(["--credentials-file", args.credentials_file])
    if args.oauth_client_file:
        cmd.extend(["--oauth-client-file", args.oauth_client_file])
    if args.delegated_user:
        cmd.extend(["--delegated-user", args.delegated_user])
    if args.verbose:
        cmd.append("--verbose")

    log = open(LOG_FILE, "a")
    proc = subprocess.Popen(
        cmd,
        stdout=log,
        stderr=log,
        start_new_session=True,
    )

    with open(PID_FILE, "w") as f:
        f.write(str(proc.pid))

    # Wait briefly to check if it started
    time.sleep(1)
    if _is_running(proc.pid):
        print(f"Workspace MCP Server started (PID {proc.pid})")
        print(f"  SSE endpoint: http://{args.host}:{args.port}/sse")
        print(f"  Log file: {LOG_FILE}")
    else:
        print("Server failed to start. Check the log file:")
        print(f"  {LOG_FILE}")


def _stop(args):
    pid = _read_pid()
    if not pid or not _is_running(pid):
        print("Server is not running.")
        if os.path.exists(PID_FILE):
            os.remove(PID_FILE)
        return

    os.kill(pid, signal.SIGTERM)
    # Wait for process to stop
    for _ in range(10):
        if not _is_running(pid):
            break
        time.sleep(0.5)

    if _is_running(pid):
        os.kill(pid, signal.SIGKILL)

    if os.path.exists(PID_FILE):
        os.remove(PID_FILE)
    print(f"Server stopped (PID {pid}).")


def _status(args):
    pid = _read_pid()
    if pid and _is_running(pid):
        print(f"Server is running (PID {pid})")
    else:
        print("Server is not running.")
        if pid and os.path.exists(PID_FILE):
            os.remove(PID_FILE)


def _run_server(args):
    """Run the server in the foreground (blocking)."""
    from onit_workspace.server import WorkspaceMCPServer

    server = WorkspaceMCPServer(
        host=args.host,
        port=args.port,
        credentials_file=getattr(args, "credentials_file", None),
        oauth_client_file=getattr(args, "oauth_client_file", None),
        delegated_user=getattr(args, "delegated_user", None),
        verbose=getattr(args, "verbose", False),
    )
    server.start()


def main():
    parser = argparse.ArgumentParser(
        prog="onit-workspace",
        description="Google Workspace MCP Server over SSE",
    )
    subparsers = parser.add_subparsers(dest="command")

    # start command
    start_parser = subparsers.add_parser("start", help="Start the server")
    start_parser.add_argument("--host", default="0.0.0.0", help="Host to bind to (default: 0.0.0.0)")
    start_parser.add_argument("--port", type=int, default=18204, help="Port to listen on (default: 18204)")
    start_parser.add_argument("--foreground", action="store_true", help="Run in foreground (don't daemonize)")
    start_parser.add_argument("--credentials-file", help="Path to Google service account JSON key")
    start_parser.add_argument("--oauth-client-file", help="Path to OAuth 2.0 client secrets JSON (Desktop app type)")
    start_parser.add_argument("--delegated-user", help="Default email for Gmail domain-wide delegation")
    start_parser.add_argument("--verbose", action="store_true", help="Enable verbose logging")

    # stop command
    subparsers.add_parser("stop", help="Stop the server")

    # status command
    subparsers.add_parser("status", help="Check server status")

    args = parser.parse_args()

    if args.command == "stop":
        _stop(args)
    elif args.command == "status":
        _status(args)
    else:
        # Default to start (handles both `onit-workspace` and `onit-workspace start`)
        if args.command is None:
            # Re-parse with start defaults
            args = start_parser.parse_args([])
        _start(args)


if __name__ == "__main__":
    main()
