# pylint: disable=import-outside-toplevel

"""
Unified video path resolution utility.

Handles 4 path types:
1. Local filesystem: /path/to/video.mp4
2. HTTP(S) URLs: https://example.com/video.mp4
3. S3 paths: s3://bucket/key.mp4
4. MinIO paths: s3://videos/video.mp4 (same as S3, uses STORAGE_* env vars)

This utility ensures all processors receive valid local filesystem paths,
regardless of the original video location.
"""

import logging
import os
import tempfile
from urllib.parse import urlparse

logger = logging.getLogger(__name__)


def resolve_video_path(video_path: str, temp_dir: str = None) -> str:
    """
    Resolve any video path to a local filesystem path.

    Handles:
    - Local paths: Return as-is (validates existence)
    - HTTP(S) URLs: Download to temp_dir
    - S3/MinIO paths (s3://): Download using StorageFactory

    Args:
        video_path: Path, URL, or S3 URI
        temp_dir: Directory for downloaded files (creates if None)

    Returns:
        Local filesystem path to video

    Raises:
        FileNotFoundError: If local path doesn't exist
        ValueError: If path type is unsupported or download fails
        RuntimeError: If download fails

    Example:
        # Local path
        path = resolve_video_path("/path/to/video.mp4")

        # HTTP(S) URL
        path = resolve_video_path("https://example.com/video.mp4")

        # S3 path (requires STORAGE_* env vars)
        path = resolve_video_path("s3://bucket/video.mp4")
    """
    if "://" in video_path and not video_path.startswith(
        ("http://", "https://", "s3://", "file://")
    ):
        raise ValueError(f"Unsupported video path format: {video_path}")

    if video_path.startswith("file://"):
        video_path = video_path[7:]

    if not video_path.startswith(("http://", "https://", "s3://")):
        if not os.path.exists(video_path):
            raise FileNotFoundError(f"Video file not found: {video_path}")
        logger.debug(f"Using local path: {video_path}")
        return video_path

    if temp_dir is None:
        temp_dir = tempfile.mkdtemp(prefix="videorag_")
        logger.debug(f"Created temporary directory: {temp_dir}")

    if video_path.startswith(("http://", "https://")):
        from mini_videorag.utils.download_video import download_video_from_url

        parsed = urlparse(video_path)
        filename = os.path.basename(parsed.path) or "video.mp4"
        local_path = os.path.join(temp_dir, filename)

        logger.info(f"Downloading HTTP(S) video: {video_path} → {local_path}")
        download_video_from_url(video_path, local_path)
        return local_path

    if video_path.startswith("s3://"):
        from mini_videorag.storage.factory import StorageFactory

        parsed = urlparse(video_path)
        bucket = parsed.netloc
        key = parsed.path.lstrip("/")

        if not key:
            raise ValueError(f"Invalid S3 path (missing key): {video_path}")

        filename = os.path.basename(key) or "video.mp4"
        local_path = os.path.join(temp_dir, filename)

        logger.info(f"Downloading S3 video: {video_path} → {local_path}")

        try:
            storage = StorageFactory.from_env()

            if bucket != storage.bucket_name:
                logger.warning(
                    f"S3 URI bucket '{bucket}' differs from env STORAGE_BUCKET_NAME "
                    f"'{storage.bucket_name}'. Using URI bucket."
                )
                storage = StorageFactory.create(
                    storage_type=os.getenv("STORAGE_TYPE", "s3"),
                    bucket_name=bucket,
                    endpoint_url=os.getenv("STORAGE_ENDPOINT_URL"),
                    region=os.getenv("STORAGE_REGION", "us-east-1"),
                    access_key=os.getenv("STORAGE_ACCESS_KEY"),
                    secret_key=os.getenv("STORAGE_SECRET_KEY"),
                )

            storage.download_to_path(key, local_path)

            logger.info(f"Successfully downloaded {key} from S3")
            return local_path

        except Exception as e:
            raise ValueError(f"Failed to download from S3 path {video_path}: {e}") from e

    raise ValueError(f"Unsupported video path format: {video_path}")
