"""CLI entry point for running Outpost9 agents locally."""

import argparse
import sys
import importlib
import os

# Explicitly import the outpost9 package to trigger __init__.py
# This sets up auto-logging and message capture
import outpost9  # noqa: F401


def main():
    """Main entry point for the outpost9-serve command."""
    parser = argparse.ArgumentParser(
        description="Run an Outpost9 agent server locally"
    )
    parser.add_argument(
        "--host",
        default="0.0.0.0",
        help="Host to bind to (default: 0.0.0.0)",
    )
    parser.add_argument(
        "--port",
        type=int,
        default=8000,
        help="Port to listen on (default: 8000)",
    )
    parser.add_argument(
        "--reload",
        action="store_true",
        help="Enable auto-reload for development",
    )
    parser.add_argument(
        "module",
        nargs="?",
        default="agent",
        help="Python module containing routes (default: agent)",
    )

    args = parser.parse_args()

    # Add current directory to path
    sys.path.insert(0, os.getcwd())

    # Import the user's module to register routes
    try:
        importlib.import_module(args.module)
    except ModuleNotFoundError as e:
        print(f"Error: Could not import module '{args.module}'")
        print(f"  {e}")
        print("\nMake sure you're in a directory with an agent.py file,")
        print("or specify the module name with: outpost9-serve <module>")
        sys.exit(1)

    # Run the server
    from .app import run_server

    print(f"Starting Outpost9 agent server...")
    print(f"  Module: {args.module}")
    print(f"  URL: http://{args.host}:{args.port}")
    print()

    run_server(host=args.host, port=args.port, reload=args.reload)


if __name__ == "__main__":
    main()
