from __future__ import annotations

from urllib.parse import urlparse

MAX_URL_LENGTH = 4096

_PRIVATE_HOSTNAMES = frozenset({"localhost", "127.0.0.1", "::1", "0.0.0.0"})
_PRIVATE_SUFFIXES = (".local", ".internal", ".localhost")


def pre_validate_url(raw: str) -> tuple[bool, str]:
    """
    Thin pre-validation before forwarding to the backend.
    Returns (ok, error_message). error_message is empty on success.
    """
    if not raw or not raw.strip():
        return False, "URL must be a non-empty string."

    if len(raw) > MAX_URL_LENGTH:
        return False, f"URL exceeds maximum length ({MAX_URL_LENGTH} characters)."

    try:
        parsed = urlparse(raw)
    except Exception:
        return False, "URL is not valid."

    if parsed.scheme != "https":
        return False, "Only HTTPS URLs are allowed."

    if parsed.username or parsed.password:
        return False, "URLs with credentials are not allowed."

    hostname = (parsed.hostname or "").lower()
    if not hostname:
        return False, "URL is not valid."

    if hostname in _PRIVATE_HOSTNAMES or any(hostname.endswith(s) for s in _PRIVATE_SUFFIXES):
        return False, "URL points to a private/local address."

    return True, ""
