#!/usr/bin/env python3
"""
CLI entry point for UASS MCP Server.

This module provides the main() function that is called when users run:
    uass-mcp-server --backend redis
"""

import asyncio
import argparse
from mcp.server.stdio import stdio_server

from uass import UASSClient
from uass.backends import RedisBackend, MemoryBackend, PostgreSQLBackend
from uass.mcp_server import UASSMCPServer


def create_backend(args):
    """Create a backend based on command-line arguments."""
    if args.backend == "memory":
        return MemoryBackend()
    elif args.backend == "redis":
        return RedisBackend(host=args.host, port=args.port)
    elif args.backend == "postgresql":
        return PostgreSQLBackend(connection_string=args.db_url)
    else:
        raise ValueError(f"Unknown backend: {args.backend}")


async def async_main():
    """Async main entry point for the MCP server."""
    parser = argparse.ArgumentParser(
        description="UASS MCP Server - Model Context Protocol server for UASS"
    )
    parser.add_argument(
        "--backend",
        choices=["memory", "redis", "postgresql"],
        default="memory",
        help="Backend to use for state storage (default: memory)"
    )
    parser.add_argument(
        "--host",
        default="localhost",
        help="Redis host (only for redis backend, default: localhost)"
    )
    parser.add_argument(
        "--port",
        type=int,
        default=6379,
        help="Redis port (only for redis backend, default: 6379)"
    )
    parser.add_argument(
        "--db-url",
        help="PostgreSQL connection string (only for postgresql backend)"
    )
    
    args = parser.parse_args()
    
    # Create backend and client
    backend = create_backend(args)
    client = UASSClient(backend=backend)
    
    # Create MCP server
    mcp_server = UASSMCPServer(client)
    
    # Run the server
    async with stdio_server() as (read_stream, write_stream):
        await mcp_server.get_server().run(
            read_stream,
            write_stream,
            mcp_server.get_server().create_initialization_options()
        )


def main():
    """Main entry point for the CLI."""
    asyncio.run(async_main())


if __name__ == "__main__":
    main()
