"""
Web Server CLI

Command-line interface for starting the web server.
"""

from __future__ import annotations

import argparse
import logging
import sys
from pathlib import Path

# Add project root to path
project_root = Path(__file__).parent.parent.parent

from shared.config import DEFAULT_DPI


def setup_logging(debug: bool = False) -> None:
    """Configure logging."""
    level = logging.DEBUG if debug else logging.INFO
    logging.basicConfig(
        level=level,
        format="%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",
        datefmt="%Y-%m-%d %H:%M:%S",
    )


def parse_args() -> argparse.Namespace:
    """Parse command-line arguments."""
    parser = argparse.ArgumentParser(
        description="Start the Invoice Field Extraction web server",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    parser.add_argument(
        "--host",
        type=str,
        default="0.0.0.0",
        help="Host to bind to",
    )

    parser.add_argument(
        "--port",
        type=int,
        default=8000,
        help="Port to listen on",
    )

    parser.add_argument(
        "--model",
        "-m",
        type=Path,
        default=Path("runs/train/invoice_fields/weights/best.pt"),
        help="Path to YOLO model weights",
    )

    parser.add_argument(
        "--confidence",
        type=float,
        default=0.5,
        help="Detection confidence threshold",
    )

    parser.add_argument(
        "--dpi",
        type=int,
        default=DEFAULT_DPI,
        help=f"DPI for PDF rendering (default: {DEFAULT_DPI}, must match training DPI)",
    )

    parser.add_argument(
        "--no-gpu",
        action="store_true",
        help="Disable GPU acceleration",
    )

    parser.add_argument(
        "--reload",
        action="store_true",
        help="Enable auto-reload for development",
    )

    parser.add_argument(
        "--workers",
        type=int,
        default=1,
        help="Number of worker processes",
    )

    parser.add_argument(
        "--debug",
        action="store_true",
        help="Enable debug mode",
    )

    return parser.parse_args()


def main() -> None:
    """Main entry point."""
    args = parse_args()
    setup_logging(debug=args.debug)

    logger = logging.getLogger(__name__)

    # Validate model path
    if not args.model.exists():
        logger.error(f"Model file not found: {args.model}")
        sys.exit(1)

    logger.info("=" * 60)
    logger.info("Invoice Field Extraction Web Server")
    logger.info("=" * 60)
    logger.info(f"Model: {args.model}")
    logger.info(f"Confidence threshold: {args.confidence}")
    logger.info(f"GPU enabled: {not args.no_gpu}")
    logger.info(f"Server: http://{args.host}:{args.port}")
    logger.info("=" * 60)

    # Create config
    from backend.web.config import AppConfig, ModelConfig, ServerConfig, FileConfig

    config = AppConfig(
        model=ModelConfig(
            model_path=args.model,
            confidence_threshold=args.confidence,
            use_gpu=not args.no_gpu,
            dpi=args.dpi,
        ),
        server=ServerConfig(
            host=args.host,
            port=args.port,
            debug=args.debug,
            reload=args.reload,
            workers=args.workers,
        ),
        file=FileConfig(),
    )

    # Create and run app
    import uvicorn
    from backend.web.app import create_app

    app = create_app(config)

    uvicorn.run(
        app,
        host=config.server.host,
        port=config.server.port,
        reload=config.server.reload,
        workers=config.server.workers if not config.server.reload else 1,
        log_level="debug" if config.server.debug else "info",
    )


if __name__ == "__main__":
    main()
