from typing import List, Optional
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from app.api.deps import get_db, get_current_active_user
from app.models.ppr import Aircraft
from app.schemas.ppr import Aircraft as AircraftSchema
from app.models.ppr import User

router = APIRouter()


@router.get("/lookup/{registration}", response_model=List[AircraftSchema])
async def lookup_aircraft_by_registration(
    registration: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    Lookup aircraft by registration (clean match).
    Removes non-alphanumeric characters from input for matching.
    """
    # Clean the input registration (remove non-alphanumeric characters)
    clean_input = ''.join(c for c in registration if c.isalnum()).upper()
    
    if len(clean_input) < 4:
        return []
    
    # Query aircraft table using clean_reg column
    aircraft_list = db.query(Aircraft).filter(
        Aircraft.clean_reg.like(f"{clean_input}%")
    ).limit(10).all()
    
    return aircraft_list


@router.get("/public/lookup/{registration}", response_model=List[AircraftSchema])
async def public_lookup_aircraft_by_registration(
    registration: str,
    db: Session = Depends(get_db)
):
    """
    Public lookup aircraft by registration (clean match).
    Removes non-alphanumeric characters from input for matching.
    No authentication required.
    """
    # Clean the input registration (remove non-alphanumeric characters)
    clean_input = ''.join(c for c in registration if c.isalnum()).upper()
    
    if len(clean_input) < 4:
        return []
    
    # Query aircraft table using clean_reg column
    aircraft_list = db.query(Aircraft).filter(
        Aircraft.clean_reg.like(f"{clean_input}%")
    ).limit(10).all()
    
    return aircraft_list


@router.get("/search", response_model=List[AircraftSchema])
async def search_aircraft(
    q: Optional[str] = Query(None, description="Search query for registration, type, or manufacturer"),
    limit: int = Query(10, ge=1, le=100, description="Maximum number of results"),
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_active_user)
):
    """
    Search aircraft by registration, type code, or manufacturer name.
    """
    if not q or len(q) < 2:
        return []
    
    # Clean search term
    clean_query = ''.join(c for c in q if c.isalnum()).upper()
    
    # Search across multiple fields
    aircraft_list = db.query(Aircraft).filter(
        (Aircraft.clean_reg.like(f"%{clean_query}%")) |
        (Aircraft.type_code.like(f"%{q.upper()}%")) |
        (Aircraft.manufacturer_name.like(f"%{q}%")) |
        (Aircraft.model.like(f"%{q}%"))
    ).limit(limit).all()
    
    return aircraft_list