from fastapi import FastAPI
from pydantic import BaseModel
from contextlib import asynccontextmanager
from fastapi.middleware.cors import CORSMiddleware
import asyncio
import rclpy
import uvicorn
import threading
import logging

import toid_cli.routers.startup as startup
import toid_cli.routers.action as action
from toid_cli.services.services import actionClient, ServerRunner, log
from toid_cli.services.runners import main_runner

logging.getLogger().setLevel(logging.INFO)

@asynccontextmanager
async def lifespan(app: FastAPI):
    rclpy.init()
    ServerRunner.setRunner(ServerRunner(app))
    thread = threading.Thread(target=rclpy.spin, args=(ServerRunner.getRunner(),), daemon=True)
    thread.start()
    log.info("Started up rclpy")
    if not hasattr(app.state, 'loop'):
        app.state.loop = asyncio.get_running_loop()

    yield

    await main_runner.stop_robot()
    log.info("Stopped robot")
    ServerRunner.getRunner().destroy_node()
    rclpy.shutdown()
    thread.join()
    log.info("Closed rclpy")



app = FastAPI(lifespan=lifespan)
app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        "*"
    ],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)



app.include_router(startup.router, prefix="/startup")
app.include_router(action.router, prefix="/action")
# store running launch processes
launch_processes = {}




def main():
    uvicorn.run(
        "toid_cli.main:app",
        host="0.0.0.0",
        port=8000,
        reload=False
    )


if __name__ == "__main__":
    main()