"""SSRF and source_url safety for video intelligence downloads."""

from __future__ import annotations

import ipaddress
import socket
from urllib.parse import urlparse

from app.services.face.video_frames import VideoFrameError

# Cloud metadata / link-local ranges (also covered by is_private / is_link_local)
_BLOCKED_HOSTNAMES = frozenset(
    {
        "localhost",
        "metadata.google.internal",
        "metadata",
        "instance-data",
    }
)


def _hostname_blocked(host: str) -> bool:
    h = (host or "").strip().lower().rstrip(".")
    if not h:
        return True
    if h in _BLOCKED_HOSTNAMES:
        return True
    if h.endswith(".localhost") or h.endswith(".local"):
        return True
    return False


def _ip_blocked(ip: ipaddress.IPv4Address | ipaddress.IPv6Address) -> bool:
    return bool(
        ip.is_private
        or ip.is_loopback
        or ip.is_link_local
        or ip.is_multicast
        or ip.is_reserved
        or ip.is_unspecified
    )


def assert_public_http_url(url: str, *, resolve_dns: bool = True) -> None:
    """Reject non-http(s) schemes and destinations that are private/loopback/metadata.

    Raises VideoFrameError with code ``ssrf_blocked`` or ``invalid_source_url``.
    """
    raw = (url or "").strip()
    parsed = urlparse(raw)
    scheme = (parsed.scheme or "").lower()
    if scheme not in {"http", "https"}:
        raise VideoFrameError(
            "Remote source_url must use http:// or https://",
            code="invalid_source_url",
        )
    host = parsed.hostname
    if not host:
        raise VideoFrameError("source_url missing hostname", code="invalid_source_url")
    if _hostname_blocked(host):
        raise VideoFrameError(
            "source_url host is not allowed (loopback/metadata)",
            code="ssrf_blocked",
        )
    # Literal IP in URL
    try:
        ip = ipaddress.ip_address(host)
        if _ip_blocked(ip):
            raise VideoFrameError(
                "source_url points to a private or reserved IP",
                code="ssrf_blocked",
            )
        return
    except ValueError:
        pass

    if not resolve_dns:
        return

    try:
        infos = socket.getaddrinfo(host, parsed.port or (443 if scheme == "https" else 80))
    except socket.gaierror as exc:
        raise VideoFrameError(
            f"source_url host could not be resolved: {host}",
            code="source_fetch_failed",
        ) from exc

    if not infos:
        raise VideoFrameError(
            f"source_url host could not be resolved: {host}",
            code="source_fetch_failed",
        )

    for info in infos:
        sockaddr = info[4]
        addr = sockaddr[0]
        try:
            ip = ipaddress.ip_address(addr)
        except ValueError:
            continue
        if _ip_blocked(ip):
            raise VideoFrameError(
                "source_url resolves to a private or reserved IP",
                code="ssrf_blocked",
            )


def looks_like_video_bytes(data: bytes) -> bool:
    """Best-effort container sniff (not a full demuxer)."""
    if not data or len(data) < 12:
        return False
    # ISO BMFF (mp4/mov) — ftyp at byte 4
    if len(data) >= 8 and data[4:8] == b"ftyp":
        return True
    if data.startswith(b"RIFF") and b"AVI" in data[:16]:
        return True
    if data.startswith(b"\x1a\x45\xdf\xa3"):  # EBML / webm/mkv
        return True
    if data[0:3] == b"\x00\x00\x01" or data.startswith(b"\x00\x00\x00\x01"):
        return True  # MPEG PES / Annex-B-ish
    # OpenCV MJPG AVI often used in tests
    if data.startswith(b"RIFF"):
        return True
    return False
