from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from typing import Optional
from sqlalchemy.orm import Session
from app.core.database import get_db
from app.core.auth import check_trip_auth
from app.schemas.trip import ParticipantCreate, ParticipantResponse
from app.models.participant import Participant
from app.models.trip import Trip

router = APIRouter()

@router.post("/{trip_id}/participants", response_model=ParticipantResponse)
async def add_participant(
    trip_id: int,
    participant: ParticipantCreate,
    db: Session = Depends(get_db),
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(HTTPBearer(auto_error=False))
):
    """Add a new participant to a trip (requires authentication if trip has password)"""
    # Check trip authentication
    trip = check_trip_auth(trip_id, credentials, db)

    # Check if participant with this name already exists in this trip
    existing = db.query(Participant).filter(
        Participant.trip_id == trip_id,
        Participant.name == participant.name,
        Participant.is_active == True
    ).first()

    if existing:
        raise HTTPException(status_code=400, detail="Participant with this name already exists")

    # Create new participant
    db_participant = Participant(
        trip_id=trip_id,
        name=participant.name,
        is_creator=False,
        is_active=True
    )
    db.add(db_participant)
    db.commit()
    db.refresh(db_participant)

    return ParticipantResponse.from_orm(db_participant)

@router.get("/{trip_id}/participants")
async def get_participants(
    trip_id: int,
    db: Session = Depends(get_db),
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(HTTPBearer(auto_error=False))
):
    """Get all participants for a trip (requires authentication if trip has password)"""
    # Check trip authentication
    trip = check_trip_auth(trip_id, credentials, db)

    participants = db.query(Participant).filter(
        Participant.trip_id == trip_id,
        Participant.is_active == True
    ).all()

    return [
        {
            "id": p.id,
            "name": p.name,
            "is_creator": p.is_creator,
            "created_at": p.created_at
        }
        for p in participants
    ]

@router.put("/{trip_id}/participants/{participant_id}/identify")
async def identify_participant(
    trip_id: int,
    participant_id: int,
    device_id: str,
    db: Session = Depends(get_db),
    credentials: Optional[HTTPAuthorizationCredentials] = Depends(HTTPBearer(auto_error=False))
):
    """Link device ID to participant for anonymous identification (requires authentication if trip has password)"""
    # Check trip authentication
    trip = check_trip_auth(trip_id, credentials, db)
    
    participant = db.query(Participant).filter(
        Participant.id == participant_id,
        Participant.trip_id == trip_id,
        Participant.is_active == True
    ).first()

    if not participant:
        raise HTTPException(status_code=404, detail="Participant not found")

    # Update device ID and last accessed
    participant.device_id = device_id
    from sqlalchemy import text
    participant.last_accessed = db.execute(text("SELECT datetime('now')")).scalar()
    db.commit()

    return {"message": "Participant identified successfully", "name": participant.name}