"""Coordination component states router."""

from fastapi import APIRouter, Depends, Query, status
from sqlalchemy.orm import Session

from api.database import get_db
from api.schemas.coord_component_state import CoordComponentStateUpsert, CoordComponentStateResponse
from api.services import coord_component_service

router = APIRouter()


@router.get("", response_model=dict, status_code=status.HTTP_200_OK)
def list_component_states(
    project_key: str | None = Query(default=None),
    db: Session = Depends(get_db),
):
    """List all component states, optionally filtered by project."""
    states = coord_component_service.get_component_states(db, project_key=project_key)
    return {
        "total": len(states),
        "states": [CoordComponentStateResponse.model_validate(s) for s in states],
    }


@router.put("/{project_key}/{component}", response_model=CoordComponentStateResponse, status_code=status.HTTP_200_OK)
def upsert_component_state(
    project_key: str,
    component: str,
    data: CoordComponentStateUpsert,
    db: Session = Depends(get_db),
):
    """Create or update the state of a component within a project."""
    state = coord_component_service.upsert_component_state(db, project_key, component, data)
    return CoordComponentStateResponse.model_validate(state)
