"""
Face Recognition API Routes
"""
from fastapi import APIRouter, HTTPException, UploadFile, File, Query

from app.services.face_service import face_service

router = APIRouter()


@router.post("/detect", summary="Detect faces in image")
async def detect_faces(
    file: UploadFile = File(...),
    landmarks: bool = Query(False, description="Return facial landmarks")
):
    """
    Detect all faces in an uploaded image
    """
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="File must be an image")

    contents = await file.read()
    result = await face_service.detect_faces(contents, landmarks)

    return {
        "filename": file.filename,
        **result
    }


@router.post("/encoding", summary="Get face encoding")
async def get_encoding(file: UploadFile = File(...)):
    """
    Get face encoding for a single face image
    """
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="File must be an image")

    contents = await file.read()
    result = await face_service.get_face_encoding(contents)

    if "error" in result:
        raise HTTPException(status_code=400, detail=result["error"])

    return {
        "filename": file.filename,
        **result
    }


@router.post("/verify", summary="Verify if two faces match")
async def verify_faces(
    image1: UploadFile = File(...),
    image2: UploadFile = File(...),
    tolerance: float = Query(0.6, ge=0.3, le=0.8, description="Distance threshold (lower = stricter)")
):
    """
    Verify if two images contain the same person
    """
    if not image1.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Image 1 must be an image file")
    if not image2.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Image 2 must be an image file")

    contents1 = await image1.read()
    contents2 = await image2.read()

    result = await face_service.verify_faces(contents1, contents2, tolerance)

    if "error" in result:
        raise HTTPException(status_code=400, detail=result["error"])

    return {
        "image1": image1.filename,
        "image2": image2.filename,
        **result
    }


@router.post("/find", summary="Find person in group photo")
async def find_in_group(
    target: UploadFile = File(...),
    group: UploadFile = File(...),
    tolerance: float = Query(0.6, ge=0.3, le=0.8)
):
    """
    Find a specific person in a group photo
    """
    if not target.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Target must be an image file")
    if not group.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="Group photo must be an image file")

    target_contents = await target.read()
    group_contents = await group.read()

    result = await face_service.find_face_in_group(target_contents, group_contents, tolerance)

    if "error" in result:
        raise HTTPException(status_code=400, detail=result["error"])

    return {
        "target_filename": target.filename,
        "group_filename": group.filename,
        **result
    }


@router.post("/analyze", summary="Analyze facial features")
async def analyze_face(file: UploadFile = File(...)):
    """
    Analyze facial features
    """
    if not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="File must be an image")

    contents = await file.read()
    result = await face_service.analyze_face(contents)

    if "error" in result:
        raise HTTPException(status_code=400, detail=result["error"])

    return {
        "filename": file.filename,
        **result
    }
