from importlib.metadata import version

from fastapi import status
from mosayic import app

from mosaygent.logger import get_logger
from mosaygent.routes import router
from mosaygent.services.environment import EnvironmentService
from mosaygent.services.expo import ExpoService

logger = get_logger(__name__)

__all__ = ['app']


# Initialize environment service
logger.info("Initializing environment service")
app.state.environment_service = EnvironmentService()

# Initialize Expo service if React Native directory is available
expo_dir = None
if app.state.environment_service.project_dir:
    expo_dir = app.state.environment_service._find_react_native_codebase()
    if expo_dir:
        logger.info(f"Initializing Expo service: {expo_dir}")
        app.state.expo_service = ExpoService(app_dir=expo_dir)
    else:
        logger.info("No React Native directory found, Expo service not initialized")
else:
    logger.info("Project directory not set, Expo service not initialized")


# Add health check endpoint
@app.get("/health", status_code=status.HTTP_200_OK, include_in_schema=False)
async def health() -> dict:
    """Health check endpoint."""
    return {"healthy": True, "version": version("mosaygent")}


# Add dev routes to the mosayic app
app.include_router(router)
logger.info("Mosaygent development routes registered")


@app.on_event("shutdown")
async def shutdown_expo_service():
    """Clean up Expo service on shutdown."""
    if hasattr(app.state, 'expo_service'):
        expo_service = app.state.expo_service
        if expo_service.process and expo_service.process.poll() is None:
            logger.info("Stopping Expo service")
            expo_service.stop()
