"""
Unified BioPype Builder Launcher.

Starts FastAPI backend and serves React UI (or Panel as fallback).
Usage: python -m biopype_builder.builder [pipeline.yaml]
"""

import os
import sys
from pathlib import Path

import uvicorn


def main():
    """Launch Bio-Pype builder."""
    import argparse

    parser = argparse.ArgumentParser(description="Bio-Pype Builder")
    parser.add_argument("--host", default="0.0.0.0", help="Host to bind to")
    parser.add_argument("--port", type=int, default=8000, help="Port to run on")
    parser.add_argument(
        "--reload", action="store_true", help="Enable auto-reload (development)"
    )
    parser.add_argument(
        "--pype-modules",
        help="Path to PYPE_MODULES directory (overrides PYPE_MODULES env var)",
    )

    args = parser.parse_args()

    if args.pype_modules:
        os.environ["PYPE_MODULES"] = str(
            Path(args.pype_modules).expanduser().absolute()
        )

    # Check PYPE_MODULES
    # if not pype_modules:
    #     print("Error: PYPE_MODULES not set")
    #     print()
    #     print("Usage:")
    #     print("  biopype-builder --pype-modules /path/to/modules [pipeline.yaml]")
    #     print("  PYPE_MODULES=/path/to/modules biopype-builder [pipeline.yaml]")
    #     print()
    #     print("Examples:")
    #     print("  biopype-builder --pype-modules ~/src/pype_modules/somatic")
    #     print(
    #         "  biopype-builder --pype-modules ~/src/pype_modules/somatic my_pipeline.yaml"
    #     )
    #     print()
    #     sys.exit(1)

    # Launch FastAPI + React
    launch_react_ui(
        host=args.host,
        port=args.port,
        reload=args.reload,
    )


def launch_react_ui(
    host: str = "0.0.0.0",
    port: int = 8000,
    reload: bool = False,
):
    # lazy load pype.__config__ to allow custom setting of PYPE_MODULES
    from pype import __config__ as pype_config

    """Launch FastAPI backend with React UI."""
    pype_modules = os.path.dirname(pype_config.PYPE_PIPELINES.__path__[0])

    print("=" * 60)
    print("Bio-Pype Builder")
    print("=" * 60)
    print(f"PYPE_MODULES: {pype_modules}")
    print()
    print("Starting servers:")
    print(f"  • API Backend:  http://{host}:{port}/api/")
    print(f"  • API Docs:     http://{host}:{port}/api/docs")

    # Check if React UI is built
    react_dist = Path(__file__).parent / "ui_react" / "dist"
    if react_dist.exists():
        print(f"  • React UI:     http://{host}:{port}/")
    else:
        print("  React UI:     Not built yet (run: cd pype/ui_react && npm run build)")
        print("                  API still available at /api/")

    print()
    print("Press Ctrl+C to stop")
    print("=" * 60)
    print()

    # Run FastAPI with React serving
    uvicorn.run(
        "biopype_builder.api.app_with_ui:app",
        host=host,
        port=port,
        reload=reload,
        log_level="info",
    )


if __name__ == "__main__":
    main()
