from fastapi import HTTPException, status
from PIL import Image
import requests

from app.utils.messages import JPEG_ONLY_MESSAGE


def download_image_to_file(url: str, input_path: str, max_bytes: int) -> None:
    if not url or not url.startswith(("http://", "https://")):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Invalid URL.",
        )
    total_bytes = 0
    try:
        with requests.get(url, stream=True, timeout=20) as response:
            response.raise_for_status()
            content_type = (response.headers.get("content-type") or "").lower()
            if content_type not in {"image/jpeg", "image/jpg"}:
                raise HTTPException(
                    status_code=status.HTTP_400_BAD_REQUEST,
                    detail=JPEG_ONLY_MESSAGE,
                )
            with open(input_path, "wb") as out_file:
                for chunk in response.iter_content(chunk_size=1024 * 1024):
                    if not chunk:
                        continue
                    out_file.write(chunk)
                    total_bytes += len(chunk)
                    if total_bytes > max_bytes:
                        raise HTTPException(
                            status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
                            detail="File too large.",
                        )
    except HTTPException:
        raise
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=f"Failed to download file: {exc}",
        ) from exc
    if total_bytes == 0:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Downloaded file is empty.",
        )


def validate_jpeg_file(input_path: str) -> None:
    try:
        Image.open(input_path).verify()
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Invalid image file.",
        ) from exc
