from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session
from datetime import datetime, timedelta
from typing import Dict, Any
import asyncio
import logging
import random

from backend.database import get_db
from backend.services.snapshot import emit_status_snapshot
from backend.services.slm_status_sync import sync_slm_status_to_emitters

router = APIRouter(prefix="/api", tags=["roster"])
logger = logging.getLogger(__name__)


@router.get("/status-snapshot")
async def get_status_snapshot(db: Session = Depends(get_db)):
    """
    Calls emit_status_snapshot() to get current fleet status.
    Syncs SLM status from SLMM before generating snapshot.
    """
    # Sync SLM status from SLMM (with timeout to prevent blocking)
    try:
        await asyncio.wait_for(sync_slm_status_to_emitters(), timeout=2.0)
    except asyncio.TimeoutError:
        logger.warning("SLM status sync timed out, using cached data")
    except Exception as e:
        logger.warning(f"SLM status sync failed: {e}")

    return emit_status_snapshot()


@router.get("/roster")
def get_roster(db: Session = Depends(get_db)):
    """
    Returns list of units with their metadata and status.
    Uses mock data for now.
    """
    snapshot = emit_status_snapshot()
    units_list = []

    for unit_id, unit_data in snapshot["units"].items():
        units_list.append({
            "id": unit_id,
            "status": unit_data["status"],
            "age": unit_data["age"],
            "last_seen": unit_data["last"],
            "deployed": unit_data["deployed"],
            "note": unit_data.get("note", ""),
            "last_file": unit_data.get("fname", "")
        })

    # Sort by status priority (Missing > Pending > OK) then by ID
    status_priority = {"Missing": 0, "Pending": 1, "OK": 2}
    units_list.sort(key=lambda x: (status_priority.get(x["status"], 3), x["id"]))

    return {"units": units_list}
