"""Validation utilities for image sources (URLs and local file paths).

Prevents SSRF via dangerous URL schemes and restricts file path access
to prevent arbitrary file reads through API query parameters.
"""

from pathlib import Path
from urllib.parse import urlparse

from fastapi import HTTPException


# Image file extensions considered safe to serve
_IMAGE_EXTENSIONS = frozenset({
    ".jpg", ".jpeg", ".png", ".bmp", ".gif", ".webp", ".tiff", ".tif", ".ico",
})


def validate_image_url(url: str) -> None:
    """Validate that *url* uses a safe scheme (http/https only).

    Blocks ``file://``, ``ftp://``, ``gopher://``, and other dangerous schemes
    that could be used for SSRF.
    """
    parsed = urlparse(url)
    if parsed.scheme not in ("http", "https"):
        raise HTTPException(
            status_code=400,
            detail=f"Unsupported URL scheme: {parsed.scheme!r}. Only http and https are allowed.",
        )

    if not parsed.hostname:
        raise HTTPException(status_code=400, detail="URL has no hostname")


def validate_image_path(file_path: str | Path) -> Path:
    """Validate a local file path points to a real image file.

    Checks:
    - The extension is a known image format
    - The resolved path does not escape via symlinks to unexpected locations

    Returns the resolved Path on success, raises HTTPException on violation.
    """
    resolved = Path(file_path).resolve()

    suffix = resolved.suffix.lower()
    if suffix not in _IMAGE_EXTENSIONS:
        raise HTTPException(
            status_code=400,
            detail=f"Unsupported file type: {suffix!r}. Only image files are allowed.",
        )

    return resolved
