"""
Mini VideoRAG CLI entry point.

Simplified to directly start the FastAPI server without CLI abstraction overhead.
"""

import asyncio
import logging
import os
import sys
from argparse import ArgumentParser
from typing import List

import uvicorn
from dotenv import load_dotenv

from mini_videorag.temporal.api.app import create_app

logger = logging.getLogger(__name__)


async def main(sys_args: List[str]):
    """
    Main entry point for Mini VideoRAG API server.

    Usage:
        python -m mini_videorag [--host HOST] [--port PORT] [--config-file PATH] [--env-file PATH]
    """
    parser = ArgumentParser(
        prog="mini_videorag",
        description="Mini VideoRAG - Multi-modal video analysis with AI-powered RAG",
    )

    parser.add_argument(
        "-c",
        "--config-file",
        dest="config_file",
        help="Configuration file path (default: auto-detect from config/video_rag_config.yml)",
        default=None,
    )
    parser.add_argument(
        "-e",
        "--env-file",
        dest="env_files",
        action="append",
        help="Environment files to load (can be specified multiple times)",
        default=[],
    )

    parser.add_argument(
        "--host",
        default="0.0.0.0",
        help="Host to bind the API server (default: 0.0.0.0)",
    )
    parser.add_argument(
        "--port",
        type=int,
        default=8000,
        help="Port to bind the API server (default: 8000)",
    )

    args = parser.parse_args(sys_args)

    for env_path in args.env_files:
        if os.path.isfile(env_path):
            load_dotenv(env_path)
            logger.info(f"Loaded environment from: {env_path}")
        else:
            sys.stderr.write(f"Warning: Environment file not found: {env_path}\n")
            sys.stderr.flush()

    default_env_path = os.path.join(os.getcwd(), ".env")
    if os.path.isfile(default_env_path):
        load_dotenv(default_env_path)
        logger.debug(f"Loaded environment from: {default_env_path}")

    if args.config_file:
        config_path = os.path.abspath(args.config_file)
        if os.path.isfile(config_path):
            os.environ["VIDEORAG_CONFIG_FILE"] = config_path
            logger.info(f"Using config file: {config_path}")
        else:
            sys.stderr.write(f"Error: Config file not found: {config_path}\n")
            sys.stderr.flush()
            sys.exit(1)

    logger.info(f"🚀 Server starting on http://{args.host}:{args.port}")
    logger.info(f"📖 Swagger UI available at: http://{args.host}:{args.port}/docs")

    app = create_app([])

    uvicorn_config = uvicorn.Config(app, host=args.host, port=args.port, log_level="info")
    server = uvicorn.Server(uvicorn_config)
    await server.serve()


if __name__ == "__main__":
    asyncio.run(main(sys.argv[1:]))
