from typing import List, Optional
from sqlalchemy.orm import Session
from sqlalchemy import desc
from datetime import datetime
from app.models.circuit import Circuit
from app.schemas.circuit import CircuitCreate, CircuitUpdate


class CRUDCircuit:
    def get(self, db: Session, circuit_id: int) -> Optional[Circuit]:
        return db.query(Circuit).filter(Circuit.id == circuit_id).first()

    def get_by_local_flight(self, db: Session, local_flight_id: int) -> List[Circuit]:
        """Get all circuits for a specific local flight"""
        return db.query(Circuit).filter(
            Circuit.local_flight_id == local_flight_id
        ).order_by(Circuit.circuit_timestamp).all()

    def get_multi(
        self, 
        db: Session, 
        skip: int = 0, 
        limit: int = 100
    ) -> List[Circuit]:
        return db.query(Circuit).order_by(desc(Circuit.created_at)).offset(skip).limit(limit).all()

    def create(self, db: Session, obj_in: CircuitCreate) -> Circuit:
        db_obj = Circuit(
            local_flight_id=obj_in.local_flight_id,
            circuit_timestamp=obj_in.circuit_timestamp
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def update(self, db: Session, db_obj: Circuit, obj_in: CircuitUpdate) -> Circuit:
        obj_data = obj_in.dict(exclude_unset=True)
        for field, value in obj_data.items():
            setattr(db_obj, field, value)
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def delete(self, db: Session, circuit_id: int) -> bool:
        circuit = self.get(db, circuit_id)
        if circuit:
            db.delete(circuit)
            db.commit()
            return True
        return False


crud_circuit = CRUDCircuit()
