from fastapi import APIRouter, HTTPException
from typing import Optional
from app.services import simulation

router = APIRouter()


@router.get("/colonias")
def list_colonias():
    return simulation.get_colonias()


@router.get("/eta")
def get_eta(colonia: Optional[str] = None, routeId: Optional[str] = None):
    # Resolver routeId a partir de colonia si es necesario
    if routeId is None:
        if colonia is None:
            raise HTTPException(status_code=400, detail="colonia or routeId required")
        mapping = simulation.get_colonias()
        match = next((c for c in mapping if c.get("colonia","").lower() == colonia.lower()), None)
        if not match:
            raise HTTPException(status_code=404, detail="colonia not found")
        routeId = match["routeId"]

    pos = simulation.get_route_position(routeId)
    status = simulation.get_route_status(routeId)
    if pos is None:
        raise HTTPException(status_code=404, detail="route not found")

    if pos < 4:
        mensaje = "El camión va en camino a tu sector"
    elif pos == 4:
        mensaje = "Llega en aproximadamente 15 minutos"
    elif pos < 8:
        mensaje = "Está atendiendo tu zona; saca tus bolsas"
    else:
        mensaje = "Servicio del día finalizado"

    return {"mensaje": mensaje, "status": status, "routeId": routeId}


@router.post("/simulate/tick")
def simulate_tick():
    events = simulation.tick()
    return {"events": events}
