"""
AI Studio Proxy - Command Line Interface

Provides CLI entry points for the proxy server and LLM mock service.
"""

import argparse
import os
import sys


def main():
    """
    Main entry point for the AI Studio Proxy server.
    
    Usage:
        $ aistudio-proxy
        $ aistudio-proxy --port 8080
        $ aistudio-proxy --host 127.0.0.1 --port 8080 --log-level debug
    """
    parser = argparse.ArgumentParser(
        prog="aistudio-proxy",
        description="AI Studio Proxy Server - OpenAI-compatible API proxy for Google AI Studio",
    )
    parser.add_argument(
        "--host",
        type=str,
        default=os.environ.get("HOST", "0.0.0.0"),
        help="Host address to bind to (default: 0.0.0.0)",
    )
    parser.add_argument(
        "--port", "-p",
        type=int,
        default=int(os.environ.get("PORT", 2048)),
        help="Port number to listen on (default: 2048)",
    )
    parser.add_argument(
        "--log-level",
        type=str,
        default=os.environ.get("LOG_LEVEL", "info"),
        choices=["debug", "info", "warning", "error", "critical"],
        help="Logging level (default: info)",
    )
    parser.add_argument(
        "--access-log",
        action="store_true",
        help="Enable access logging",
    )
    parser.add_argument(
        "--reload",
        action="store_true",
        help="Enable auto-reload for development",
    )
    parser.add_argument(
        "--version", "-v",
        action="version",
        version="%(prog)s 0.1.0",
    )
    
    args = parser.parse_args()
    
    from .server import run_server
    
    print(f"Starting AI Studio Proxy Server on {args.host}:{args.port}")
    run_server(
        host=args.host,
        port=args.port,
        log_level=args.log_level,
        access_log=args.access_log,
        reload=args.reload,
    )


def llm_main():
    """
    Entry point for the LLM mock service (Ollama-compatible).
    
    Usage:
        $ aistudio-llm
        $ aistudio-llm --main-server-port 8080
    """
    # Import and run the llm module's main function
    # We need to set up the path to find the llm module
    import importlib.util
    
    # Try to import from the installed package location first
    try:
        from . import _llm_service
        _llm_service.main()
    except ImportError:
        # Fallback: run the original llm.py
        parser = argparse.ArgumentParser(
            prog="aistudio-llm",
            description="LLM Mock Service - Ollama-compatible API for AI Studio Proxy",
        )
        parser.add_argument(
            "--main-server-port",
            type=int,
            default=int(os.environ.get("MAIN_SERVER_PORT", 2048)),
            help="Port of the main AI Studio Proxy server (default: 2048)",
        )
        parser.add_argument(
            "--port",
            type=int,
            default=11434,
            help="Port for the LLM service (default: 11434)",
        )
        parser.add_argument(
            "--version", "-v",
            action="version",
            version="%(prog)s 0.1.0",
        )
        
        args = parser.parse_args()
        
        # Set environment variable for the main server port
        os.environ["MAIN_SERVER_PORT"] = str(args.main_server_port)
        
        # Import and run Flask app
        try:
            # Try importing from package
            from ._llm_service import app, API_URL
            import logging
            
            logger = logging.getLogger(__name__)
            logger.info(f"Starting LLM Mock Service on port {args.port}")
            logger.info(f"Forwarding requests to: http://localhost:{args.main_server_port}/v1/chat/completions")
            
            app.run(host="0.0.0.0", port=args.port, debug=False)
        except ImportError:
            print("Error: Could not import LLM service module.", file=sys.stderr)
            print("Please ensure the package is properly installed.", file=sys.stderr)
            sys.exit(1)


if __name__ == "__main__":
    main()
