"""Background removal (segmentation / 누끼) endpoint."""

from fastapi import APIRouter, Depends, File, Query, UploadFile

from app.dependencies import get_segmentation_service
from app.schemas.segmentation import RemoveBackgroundResponse
from app.services.segmentation_service import SegmentationService
from app.utils.image import save_segmentation_image

router = APIRouter(prefix="/api/v1/segmentation", tags=["segmentation"])


@router.post("/remove-bg", response_model=RemoveBackgroundResponse)
def remove_background(
    image: UploadFile = File(...),
    center_crop: bool = Query(
        False, description="Center-crop person in 9:16 aspect ratio"
    ),
    seg_svc: SegmentationService = Depends(get_segmentation_service),
) -> RemoveBackgroundResponse:
    """Remove background from uploaded image.

    Accepts any common image format (JPEG, PNG, WebP).
    Saves the result as PNG with transparent background and returns the URL.
    When center_crop=true, the result is cropped to 9:16 with the person
    centered and minimal top/bottom margins.
    """
    image_bytes = image.file.read()
    result_bytes = seg_svc.remove_background(image_bytes, center_crop=center_crop)
    relative_path = save_segmentation_image(result_bytes)
    return RemoveBackgroundResponse(image_url=f"/storage/{relative_path}")
