from typing import List
from fastapi import APIRouter, Depends, HTTPException, status, Request
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_read_user, get_current_operator_user
from app.crud.crud_circuit import crud_circuit
from app.schemas.circuit import Circuit, CircuitCreate, CircuitUpdate
from app.models.ppr import User
from app.core.utils import get_client_ip

router = APIRouter()


@router.get("/", response_model=List[Circuit])
async def get_circuits(
    skip: int = 0,
    limit: int = 100,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_read_user)
):
    """Get circuit records"""
    circuits = crud_circuit.get_multi(db, skip=skip, limit=limit)
    return circuits


@router.get("/flight/{local_flight_id}", response_model=List[Circuit])
async def get_circuits_by_flight(
    local_flight_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_read_user)
):
    """Get all circuits for a specific local flight"""
    circuits = crud_circuit.get_by_local_flight(db, local_flight_id=local_flight_id)
    return circuits


@router.post("/", response_model=Circuit)
async def create_circuit(
    request: Request,
    circuit_in: CircuitCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_operator_user)
):
    """Record a new circuit (touch and go) for a local flight"""
    circuit = crud_circuit.create(db, obj_in=circuit_in)
    
    # Send real-time update via WebSocket
    if hasattr(request.app.state, 'connection_manager'):
        await request.app.state.connection_manager.broadcast({
            "type": "circuit_recorded",
            "data": {
                "id": circuit.id,
                "local_flight_id": circuit.local_flight_id,
                "circuit_timestamp": circuit.circuit_timestamp.isoformat()
            }
        })
    
    return circuit


@router.get("/{circuit_id}", response_model=Circuit)
async def get_circuit(
    circuit_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_read_user)
):
    """Get a specific circuit record"""
    circuit = crud_circuit.get(db, circuit_id=circuit_id)
    if not circuit:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Circuit record not found"
        )
    return circuit


@router.put("/{circuit_id}", response_model=Circuit)
async def update_circuit(
    circuit_id: int,
    circuit_in: CircuitUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_operator_user)
):
    """Update a circuit record"""
    circuit = crud_circuit.get(db, circuit_id=circuit_id)
    if not circuit:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Circuit record not found"
        )
    circuit = crud_circuit.update(db, db_obj=circuit, obj_in=circuit_in)
    return circuit


@router.delete("/{circuit_id}")
async def delete_circuit(
    circuit_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_operator_user)
):
    """Delete a circuit record"""
    circuit = crud_circuit.get(db, circuit_id=circuit_id)
    if not circuit:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Circuit record not found"
        )
    crud_circuit.delete(db, circuit_id=circuit_id)
    return {"detail": "Circuit record deleted"}
