"""CLI entry point for Whisper Scribe."""

import argparse
import webbrowser
from threading import Timer

import uvicorn

from . import __version__, __app_name__


def open_browser(port: int):
    """Open browser after a short delay."""
    webbrowser.open(f"http://localhost:{port}")


def main():
    parser = argparse.ArgumentParser(
        prog="whisper-scribe",
        description=f"{__app_name__} - YouTube video transcription using OpenAI Whisper"
    )
    parser.add_argument(
        "--version", "-v",
        action="version",
        version=f"{__app_name__} {__version__}"
    )
    parser.add_argument(
        "--port", "-p",
        type=int,
        default=8000,
        help="Port to run the server on (default: 8000)"
    )
    parser.add_argument(
        "--host",
        type=str,
        default="127.0.0.1",
        help="Host to bind to (default: 127.0.0.1)"
    )
    parser.add_argument(
        "--no-browser",
        action="store_true",
        help="Don't open browser automatically"
    )
    parser.add_argument(
        "--reload",
        action="store_true",
        help="Enable auto-reload for development"
    )

    args = parser.parse_args()

    print(f"\n  {__app_name__} v{__version__}")
    print(f"  Starting server at http://{args.host}:{args.port}")
    print("  Press Ctrl+C to stop\n")

    if not args.no_browser and args.host in ("127.0.0.1", "localhost"):
        Timer(1.5, open_browser, [args.port]).start()

    uvicorn.run(
        "whisper_scribe.app:app",
        host=args.host,
        port=args.port,
        reload=args.reload,
        log_level="info"
    )


if __name__ == "__main__":
    main()
