from __future__ import annotations

import re

GOOGLE_DRIVE_FOLDER_RE = re.compile(
    r"^https?://(?:www\.)?drive\.google\.com/(?:"
    r"drive/(?:u/\d+/)?folders/[a-zA-Z0-9_-]+"
    r"|open\?id=[a-zA-Z0-9_-]+"
    r"|folderview\?id=[a-zA-Z0-9_-]+"
    r")(?:[/?#].*)?$",
    re.IGNORECASE,
)

GOOGLE_DRIVE_LINK_ERROR = "Enter a valid Google Drive folder link."


def normalize_google_drive_folder_link(link: str | None) -> str | None:
    if link is None:
        return None
    trimmed = link.strip()
    if not trimmed:
        return None
    if trimmed.startswith(("http://", "https://")):
        return trimmed
    return f"https://{trimmed}"


def validate_google_drive_folder_link(link: str | None) -> str | None:
    """Return a normalized Drive folder URL, or None when cleared. Raises ValueError if invalid."""
    normalized = normalize_google_drive_folder_link(link)
    if normalized is None:
        return None
    if not GOOGLE_DRIVE_FOLDER_RE.match(normalized):
        raise ValueError(GOOGLE_DRIVE_LINK_ERROR)
    return normalized
