"""
CLI commands for bfabric-web-apps
"""
import sys
import subprocess
from pathlib import Path
import argparse

def start():
    """Start the webapp with appropriate server (Flask dev or Gunicorn)"""
    parser = argparse.ArgumentParser(
        description="Start a B-Fabric webapp"
    )
    parser.add_argument(
        "app_module",
        help="Python module path to the app (e.g., 'index_uploader:server' or 'index_uploader:app.server')"
    )
    parser.add_argument(
        "--dev",
        action="store_true",
        help="Force development mode (Flask dev server)"
    )
    parser.add_argument(
        "--prod",
        action="store_true",
        help="Force production mode (Gunicorn)"
    )

    args = parser.parse_args()

    # Import settings to check DEBUG mode
    from bfabric_web_apps.utils.config import settings

    # Determine which server to use
    use_dev_server = args.dev or (settings.DEBUG and not args.prod)

    if use_dev_server:
        print("🔧 Starting in DEVELOPMENT mode...")
        print(f"📍 Server: http://{settings.HOST}:{settings.PORT}")
        print("⚡ Using Flask development server with auto-reload")
        print()

        # Extract module and app name for Flask
        module_path = args.app_module.split(":")[0]
        sys.argv = [sys.argv[0]]  # Clear args for the app

        # Import and run the app
        import importlib
        module = importlib.import_module(module_path.replace("/", ".").replace(".py", ""))

        # The app should have a __main__ block that runs it
        if hasattr(module, "app"):
            module.app.run(
                debug=True,
                host=settings.HOST,
                port=settings.PORT
            )
    else:
        print("🚀 Starting in PRODUCTION mode...")
        print(f"📍 Server: http://{settings.HOST}:{settings.PORT}")
        print("⚙️  Using Gunicorn with 4 workers")
        print()

        # Find gunicorn config - check multiple locations
        possible_paths = [
            Path(__file__).parent.parent / "gunicorn.conf.py",  # Development install
            Path(__file__).parent / "gunicorn.conf.py",  # Packaged install
        ]

        config_path = None
        for path in possible_paths:
            if path.exists():
                config_path = path
                break

        if not config_path:
            print("❌ Error: gunicorn.conf.py not found!")
            print("Searched in:")
            for path in possible_paths:
                print(f"  - {path}")
            sys.exit(1)

        # Start gunicorn
        cmd = [
            "gunicorn",
            args.app_module,
            "-c", str(config_path)
        ]

        try:
            subprocess.run(cmd, check=True)
        except subprocess.CalledProcessError as e:
            print(f"❌ Error starting gunicorn: {e}")
            sys.exit(1)


if __name__ == "__main__":
    start()