"""Main entry point for the FenLiu application."""

import argparse
import logging
from pathlib import Path

import uvicorn
from alembic.config import Config as AlembicConfig

from alembic import command as alembic_command
from fenliu.config import settings
from fenliu.logging import get_logger
from fenliu.logging import setup_logging


def parse_arguments() -> argparse.Namespace:
    """Parse command line arguments."""
    parser = argparse.ArgumentParser(description="FenLiu - Fediverse content stream filtering system")

    parser.add_argument(
        "--host",
        default="127.0.0.1",
        help="Host to bind the server to (default: 127.0.0.1)",
    )
    parser.add_argument(
        "--port",
        type=int,
        default=8000,
        help="Port to bind the server to (default: 8000)",
    )
    parser.add_argument(
        "--reload",
        action="store_true",
        help="Enable auto-reload for development",
    )
    parser.add_argument(
        "--debug",
        action="store_true",
        help="Enable debug mode with file logging",
    )
    parser.add_argument(
        "--log-level",
        choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
        default="INFO",
        help="Console logging level (default: INFO, file always DEBUG)",
    )
    parser.add_argument(
        "--log-dir",
        default="logs",
        help="Directory for debug log files (default: logs)",
    )

    return parser.parse_args()


def log_startup_info(args: argparse.Namespace, logger: logging.Logger) -> None:
    """Log startup information."""
    logger.info(f"Starting FenLiu v{settings.app_version}")
    logger.info(f"Listening on http://{args.host}:{args.port}")
    logger.info(f"Debug mode: {settings.debug}")
    logger.debug(f"Database: {settings.database_url}")
    if args.debug:
        logger.info(f"Debug logs written to: {args.log_dir}/fenliu_debug.log")


def main() -> None:
    """Run the FenLiu application."""
    args = parse_arguments()

    # Setup logging with debug file rotation if debug mode is enabled
    setup_logging(debug=args.debug, log_dir=args.log_dir)
    logger = get_logger(__name__)

    if args.debug:
        settings.debug = True

    logger.debug(f"Arguments parsed: host={args.host}, port={args.port}, debug={args.debug}")

    log_startup_info(args, logger)

    # Run migrations synchronously before starting the server.
    # Running alembic from a thread executor (while the asyncio event loop is active)
    # causes a deadlock: alembic's env.py calls logging.config.fileConfig() which
    # reconfigures the logging system, conflicting with concurrent log emissions from
    # the event loop. Running migrations here (no event loop, no threads) avoids this.
    alembic_ini = Path(__file__).parent.parent.parent / "alembic.ini"
    alembic_cfg = AlembicConfig(str(alembic_ini))
    alembic_command.upgrade(alembic_cfg, "head")
    # Restore our logging setup after alembic's fileConfig() reconfigures it
    setup_logging(debug=args.debug, log_dir=args.log_dir)
    logger.info("Database migrations applied")

    uvicorn.run(
        "fenliu.main:app",
        host=args.host,
        port=args.port,
        reload=args.reload,
        log_level=args.log_level.lower(),
        log_config=None,  # Disable uvicorn's default logging config to use ours
    )


if __name__ == "__main__":
    main()
