#!/usr/bin/env python3
"""
Script to check the actual resolution of downloaded MP4 files.
"""

import sys

import json
import subprocess
from pathlib import Path


def get_video_info_ffprobe(file_path):
    """Get video information using ffprobe."""
    try:
        cmd = [
            "ffprobe",
            "-v",
            "quiet",
            "-print_format",
            "json",
            "-show_streams",
            str(file_path),
        ]
        result = subprocess.run(cmd, capture_output=True, text=True, check=True)
        data = json.loads(result.stdout)

        # Find video stream
        for stream in data.get("streams", []):
            if stream.get("codec_type") == "video":
                width = stream.get("width")
                height = stream.get("height")
                codec = stream.get("codec_name")
                bitrate = stream.get("bit_rate")
                return {
                    "width": width,
                    "height": height,
                    "codec": codec,
                    "bitrate": bitrate,
                    "resolution": (
                        f"{width}x{height}" if width and height else "Unknown"
                    ),
                }
        return None
    except (
        subprocess.CalledProcessError,
        json.JSONDecodeError,
        FileNotFoundError,
    ) as e:
        return None


def get_video_info_python(file_path):
    """Get video information using Python libraries (fallback)."""
    try:
        import cv2

        cap = cv2.VideoCapture(str(file_path))
        if cap.isOpened():
            width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
            height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
            cap.release()
            return {
                "width": width,
                "height": height,
                "codec": "Unknown",
                "bitrate": None,
                "resolution": f"{width}x{height}",
            }
    except ImportError:
        pass

    try:
        from moviepy.editor import VideoFileClip

        clip = VideoFileClip(str(file_path))
        width, height = clip.size
        clip.close()
        return {
            "width": width,
            "height": height,
            "codec": "Unknown",
            "bitrate": None,
            "resolution": f"{width}x{height}",
        }
    except ImportError:
        pass

    return None


def check_resolutions(downloads_dir="downloads"):
    """Check resolutions of all MP4 files in the downloads directory."""
    downloads_path = Path(downloads_dir)

    if not downloads_path.exists():
        print(f"❌ Downloads directory '{downloads_dir}' not found!")
        return

    mp4_files = list(downloads_path.rglob("*.mp4"))

    if not mp4_files:
        print(f"❌ No MP4 files found in '{downloads_dir}'!")
        return

    print(f"🔍 Checking resolution of {len(mp4_files)} MP4 files...")
    print("=" * 80)

    resolutions = {}
    total_files = 0
    successful_checks = 0

    for mp4_file in sorted(mp4_files):
        total_files += 1
        relative_path = mp4_file.relative_to(downloads_path)

        # Try ffprobe first, then Python libraries
        info = get_video_info_ffprobe(mp4_file)
        if not info:
            info = get_video_info_python(mp4_file)

        if info:
            successful_checks += 1
            resolution = info["resolution"]
            resolutions[resolution] = resolutions.get(resolution, 0) + 1

            # Determine if it's 720p or not
            width, height = info["width"], info["height"]
            is_720p = (width == 1280 and height == 720) or (
                width == 720 and height == 1280
            )
            status = "✅ 720p" if is_720p else "❌ Not 720p"

            print(f"{status} | {resolution:>12} | {relative_path}")
        else:
            print(f"❓ Unknown | {'Unknown':>12} | {relative_path}")

    print("=" * 80)
    print(f"📊 Summary:")
    print(f"   Total files checked: {total_files}")
    print(f"   Successfully analyzed: {successful_checks}")
    print(f"   Failed to analyze: {total_files - successful_checks}")
    print()
    print("📈 Resolution breakdown:")

    for resolution, count in sorted(
        resolutions.items(), key=lambda x: x[1], reverse=True
    ):
        percentage = (count / successful_checks) * 100
        is_720p = "1280x720" in resolution or "720x1280" in resolution
        status = "✅ 720p" if is_720p else "❌ Other"
        print(
            f"   {status} | {resolution:>12} | {count:>3} files ({percentage:>5.1f}%)"
        )


def main():
    """Main function."""
    if len(sys.argv) > 1:
        downloads_dir = sys.argv[1]
    else:
        downloads_dir = "downloads"

    check_resolutions(downloads_dir)


if __name__ == "__main__":
    main()
