from fastapi import APIRouter, Depends, Query, HTTPException
from sqlmodel import Session, select
from typing import Optional
from uuid import UUID

from app.core.database import get_session
from app.models.bus_schedule import BusSchedule
from app.api.deps import get_current_admin

router = APIRouter(prefix="/api/schedules", tags=["schedules"])


@router.get("")
async def get_schedules(
    route_id: Optional[UUID] = Query(None),
    stop_id: Optional[UUID] = Query(None),
    only_published: bool = Query(True),
    session: Session = Depends(get_session)
):
    """Get schedules for a route or stop."""
    statement = select(BusSchedule)
    
    if only_published:
        statement = statement.where(BusSchedule.is_published)
        
    if route_id:
        statement = statement.where(BusSchedule.route_id == route_id)
    
    if stop_id:
        from app.models.route_stop import RouteStop
        statement = statement.join(
            RouteStop, BusSchedule.route_id == RouteStop.route_id
        ).where(RouteStop.stop_id == stop_id)
    
    schedules = session.exec(statement).all()
    return schedules

@router.post("")
async def create_schedule(
    schedule: BusSchedule,
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """Create a new bus schedule (Admin only)."""
    db_schedule = BusSchedule.model_validate(schedule)
    session.add(db_schedule)
    session.commit()
    session.refresh(db_schedule)
    return db_schedule

@router.put("/{schedule_id}")
async def update_schedule(
    schedule_id: UUID,
    schedule_update: dict,
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """Update a bus schedule (Admin only)."""
    db_schedule = session.get(BusSchedule, schedule_id)
    if not db_schedule:
        raise HTTPException(status_code=404, detail="Schedule not found")
    
    for key, value in schedule_update.items():
        if hasattr(db_schedule, key):
            setattr(db_schedule, key, value)
            
    session.add(db_schedule)
    session.commit()
    session.refresh(db_schedule)
    return db_schedule

@router.delete("/{schedule_id}")
async def delete_schedule(
    schedule_id: UUID,
    session: Session = Depends(get_session),
    _: bool = Depends(get_current_admin)
):
    """Delete a bus schedule (Admin only)."""
    db_schedule = session.get(BusSchedule, schedule_id)
    if not db_schedule:
        raise HTTPException(status_code=404, detail="Schedule not found")
        
    session.delete(db_schedule)
    session.commit()
    return {"ok": True}

