"""Coordination status overview router."""

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

from api.database import get_db
from api.schemas.coord_session_lock import CoordSessionLockResponse
from api.schemas.coord_workflow import CoordWorkflowResponse
from api.schemas.coord_component_state import CoordComponentStateResponse
from api.services import coord_lock_service, coord_workflow_service, coord_component_service, coord_message_service

router = APIRouter()


@router.get("", response_model=dict, status_code=status.HTTP_200_OK)
def get_coordination_status(
    db: Session = Depends(get_db),
):
    """Return a cross-project snapshot: active locks, in-progress workflows, component states, unread message counts."""
    active_locks, lock_total = coord_lock_service.get_active_locks(db, limit=200)
    active_workflows, wf_total = coord_workflow_service.get_workflows(db, status_filter="active", limit=200)
    component_states = coord_component_service.get_component_states(db)

    # Group active locks by project
    locks_by_project: dict = {}
    for lock in active_locks:
        locks_by_project.setdefault(lock.project_key, []).append(
            CoordSessionLockResponse.model_validate(lock)
        )

    # Group component states by project
    components_by_project: dict = {}
    for state in component_states:
        components_by_project.setdefault(state.project_key, []).append(
            CoordComponentStateResponse.model_validate(state)
        )

    return {
        "active_lock_count": lock_total,
        "active_workflow_count": wf_total,
        "locks_by_project": {k: v for k, v in locks_by_project.items()},
        "active_workflows": [CoordWorkflowResponse.model_validate(w) for w in active_workflows],
        "components_by_project": {k: v for k, v in components_by_project.items()},
    }
