import io

import redis as redis_lib
from fastapi import APIRouter, Depends, HTTPException, UploadFile, status
from PIL import Image, UnidentifiedImageError

from app.api.v1.deps import get_current_user
from app.core.config import settings
from app.db.redis import get_redis
from app.models.user import User
from app.schemas.upload import UploadResponse
from app.services.rate_limit import rate_limit_by_user
from app.services.upload import upload_image

router = APIRouter(prefix="/uploads", tags=["uploads"])

_ALLOWED_CONTENT_TYPES = {"image/jpeg", "image/png", "image/webp"}
# Pillow's own format names for the same three types — checked against
# the file's actual decoded content, not just the client-supplied
# Content-Type header above, which is trivially spoofable.
_ALLOWED_IMAGE_FORMATS = {"JPEG", "PNG", "WEBP"}

_INVALID_IMAGE = HTTPException(
    status_code=status.HTTP_400_BAD_REQUEST,
    detail="Only JPEG, PNG, or WebP images are accepted.",
)


@router.post("/image", response_model=UploadResponse)
def upload_image_endpoint(
    file: UploadFile,
    _user: User = Depends(get_current_user),
    redis: redis_lib.Redis = Depends(get_redis),
) -> UploadResponse:
    """Generic image upload, used by any feature that needs to attach a
    photo (courier profile, merchant listing, etc.) once those exist.
    Not tied to a specific domain model yet — callers just get back a
    URL and store it themselves.

    Validated twice: the Content-Type header is a cheap first filter,
    but the real check is Pillow actually decoding the bytes as one of
    the allowed formats — a renamed/relabeled non-image file fails
    here even if it claimed to be a PNG. Size is capped before either
    check touches the bytes, by reading at most one byte past the
    limit rather than the whole stream up front.

    Rate limited per user, on top of the global per-IP backstop — each
    call costs money via Cloudinary regardless of whether the image
    ends up used anywhere, so this is capped before the (cheap)
    validation above even runs."""
    rate_limit_by_user(
        redis,
        _user.id,
        "upload_image",
        settings.upload_rate_limit_max_attempts,
        settings.upload_rate_limit_window_seconds,
    )
    if file.content_type not in _ALLOWED_CONTENT_TYPES:
        raise _INVALID_IMAGE

    data = file.file.read(settings.max_upload_size_bytes + 1)
    if len(data) > settings.max_upload_size_bytes:
        max_mb = settings.max_upload_size_bytes // (1024 * 1024)
        raise HTTPException(
            status_code=status.HTTP_413_CONTENT_TOO_LARGE,
            detail=f"Images can't be larger than {max_mb}MB.",
        )

    try:
        image = Image.open(io.BytesIO(data))
        image_format = image.format
        image.verify()
    except (UnidentifiedImageError, OSError) as exc:
        raise _INVALID_IMAGE from exc
    if image_format not in _ALLOWED_IMAGE_FORMATS:
        raise _INVALID_IMAGE

    url = upload_image(io.BytesIO(data), folder="uploads")
    return UploadResponse(url=url)
