"""
Unit tests for video operations.
"""

import pytest
import numpy as np
import fmusvid

def test_grayscale(sample_video):
    """Test grayscale conversion."""
    video = fmusvid.load(sample_video)
    gray = video.grayscale()
    frame = gray.get_frame(0)
    # Grayscale can be 2D, 3D with 1 channel, or 3D with equal RGB values
    if len(frame.shape) == 3 and frame.shape[-1] == 3:
        # Check if all channels are equal (grayscale)
        assert np.allclose(frame[:, :, 0], frame[:, :, 1])
        assert np.allclose(frame[:, :, 0], frame[:, :, 2])
    else:
        assert len(frame.shape) == 2 or frame.shape[-1] == 1

def test_blur(sample_video):
    """Test blur effect."""
    video = fmusvid.load(sample_video)
    blurred = video.blur(radius=2.0)
    assert isinstance(blurred, fmusvid.Video)

def test_brightness(sample_video):
    """Test brightness adjustment."""
    video = fmusvid.load(sample_video)
    brightened = video.brightness(1.5)
    assert isinstance(brightened, fmusvid.Video)

def test_contrast(sample_video):
    """Test contrast adjustment."""
    video = fmusvid.load(sample_video)
    contrasted = video.contrast(1.5)
    assert isinstance(contrasted, fmusvid.Video)

def test_concat(sample_video):
    """Test video concatenation."""
    videos = [fmusvid.load(sample_video) for _ in range(3)]
    result = fmusvid.concat(videos)
    assert isinstance(result, fmusvid.Video)
    assert result.get_info()["duration"] == pytest.approx(15.0)  # 3 * 5 seconds

def test_grid(sample_video):
    """Test video grid creation."""
    videos = [fmusvid.load(sample_video) for _ in range(4)]
    result = fmusvid.grid(videos, rows=2, cols=2)
    assert isinstance(result, fmusvid.Video)
    info = result.get_info()
    # Grid should be 2 * 640 = 1280 wide, and scale to maintain aspect ratio
    # With 480 height, when scaled to half width (320), height becomes 240
    # So grid is 1280 wide, 480 tall (2 rows of 240)
    assert info["width"] == 1280  # 2 * 640
    assert info["height"] == 480  # 2 * 240 (scaled from 480)

def test_invalid_operation_params(sample_video):
    """Test handling of invalid operation parameters."""
    video = fmusvid.load(sample_video)

    with pytest.raises(ValueError):
        video.brightness(-1.0)

    with pytest.raises(ValueError):
        video.blur(-1.0)

    with pytest.raises(ValueError):
        video.contrast(0)

def test_operation_chaining(sample_video):
    """Test operation chaining."""
    video = fmusvid.load(sample_video)
    result = (
        video
        .trim(0, 2.0)
        .resize(width=1280)
        .grayscale()
        .blur(1.0)
    )
    assert isinstance(result, fmusvid.Video)
    info = result.get_info()
    assert info["duration"] == pytest.approx(2.0)
    assert info["width"] == 1280
