"""
Unit tests for FrameProcessor

Tests PNG to RGBA conversion, validation, and performance optimization.

Part of Issue #114 - Stream B: Image Processing & Frame Conversion
"""

import pytest
from io import BytesIO
from PIL import Image
import time

from frame_processor import FrameProcessor, OptimizedFrameProcessor


class TestFrameProcessor:
    """Tests for base FrameProcessor class"""

    @pytest.fixture
    def processor(self):
        """Create standard FrameProcessor instance"""
        return FrameProcessor(validate_dimensions=True, profile=False)

    @pytest.fixture
    def profiling_processor(self):
        """Create FrameProcessor with profiling enabled"""
        return FrameProcessor(validate_dimensions=True, profile=True)

    @pytest.fixture
    def valid_png_bytes(self):
        """Create valid 1280x720 PNG bytes"""
        img = Image.new('RGB', (1280, 720), (100, 150, 200))
        buffer = BytesIO()
        img.save(buffer, format='PNG')
        return buffer.getvalue()

    @pytest.fixture
    def valid_rgba_png_bytes(self):
        """Create valid 1280x720 RGBA PNG bytes"""
        img = Image.new('RGBA', (1280, 720), (100, 150, 200, 255))
        buffer = BytesIO()
        img.save(buffer, format='PNG')
        return buffer.getvalue()

    @pytest.fixture
    def wrong_size_png_bytes(self):
        """Create PNG with wrong dimensions"""
        img = Image.new('RGB', (640, 480), (100, 150, 200))
        buffer = BytesIO()
        img.save(buffer, format='PNG')
        return buffer.getvalue()

    def test_basic_conversion(self, processor, valid_png_bytes):
        """Test basic PNG to RGBA conversion"""
        rgba_bytes = processor.process(valid_png_bytes)

        # Verify output is bytes
        assert isinstance(rgba_bytes, bytes)

        # Verify correct length (1280 * 720 * 4)
        expected_length = 1280 * 720 * 4
        assert len(rgba_bytes) == expected_length, \
            f"Expected {expected_length} bytes, got {len(rgba_bytes)}"

    def test_rgba_input_conversion(self, processor, valid_rgba_png_bytes):
        """Test conversion when input is already RGBA PNG"""
        rgba_bytes = processor.process(valid_rgba_png_bytes)

        # Should still work correctly
        assert isinstance(rgba_bytes, bytes)
        assert len(rgba_bytes) == 1280 * 720 * 4

    def test_dimension_validation_success(self, processor, valid_png_bytes):
        """Test that correct dimensions pass validation"""
        # Should not raise any exception
        rgba_bytes = processor.process(valid_png_bytes)
        assert rgba_bytes is not None

    def test_dimension_validation_failure(self, processor, wrong_size_png_bytes):
        """Test that wrong dimensions raise ValueError"""
        with pytest.raises(ValueError, match="Invalid image dimensions"):
            processor.process(wrong_size_png_bytes)

    def test_dimension_validation_disabled(self, wrong_size_png_bytes):
        """Test processing with validation disabled"""
        processor = FrameProcessor(validate_dimensions=False, profile=False)

        # Should not raise dimension error, but will have wrong byte count
        # This will still fail on byte count validation
        with pytest.raises(ValueError, match="Invalid RGBA bytes length"):
            processor.process(wrong_size_png_bytes)

    def test_corrupt_png_bytes(self, processor):
        """Test that corrupt PNG bytes raise appropriate error"""
        corrupt_bytes = b"This is not a valid PNG file"

        # PIL should raise UnidentifiedImageError
        from PIL import UnidentifiedImageError
        with pytest.raises(UnidentifiedImageError):
            processor.process(corrupt_bytes)

    def test_empty_bytes(self, processor):
        """Test that empty bytes raise appropriate error"""
        with pytest.raises(Exception):  # Could be various exceptions
            processor.process(b"")

    def test_color_accuracy(self, processor):
        """Test that colors are preserved during conversion"""
        # Create image with specific color
        test_color = (100, 150, 200)
        img = Image.new('RGB', (1280, 720), test_color)
        buffer = BytesIO()
        img.save(buffer, format='PNG')
        png_bytes = buffer.getvalue()

        # Convert to RGBA
        rgba_bytes = processor.process(png_bytes)

        # Check first pixel (RGBA format: R, G, B, A)
        assert rgba_bytes[0] == test_color[0]  # R
        assert rgba_bytes[1] == test_color[1]  # G
        assert rgba_bytes[2] == test_color[2]  # B
        assert rgba_bytes[3] == 255  # A (opaque)

    def test_multiple_frames(self, processor, valid_png_bytes):
        """Test processing multiple frames in sequence"""
        for i in range(10):
            rgba_bytes = processor.process(valid_png_bytes)
            assert len(rgba_bytes) == 1280 * 720 * 4

    def test_performance_stats_disabled(self, processor, valid_png_bytes):
        """Test that stats work when profiling is disabled"""
        processor.process(valid_png_bytes)
        processor.process(valid_png_bytes)

        stats = processor.get_performance_stats()
        assert stats['total_frames'] == 0  # No profiling
        assert stats['avg_time_ms'] == 0.0

    def test_performance_stats_enabled(self, profiling_processor, valid_png_bytes):
        """Test that stats are collected when profiling is enabled"""
        # Process some frames
        for _ in range(5):
            profiling_processor.process(valid_png_bytes)

        stats = profiling_processor.get_performance_stats()
        assert stats['total_frames'] == 5
        assert stats['avg_time_ms'] > 0.0
        assert stats['min_time_ms'] > 0.0
        assert stats['max_time_ms'] >= stats['min_time_ms']
        assert stats['p95_time_ms'] > 0.0

    def test_reset_stats(self, profiling_processor, valid_png_bytes):
        """Test that stats can be reset"""
        # Process frames
        profiling_processor.process(valid_png_bytes)
        profiling_processor.process(valid_png_bytes)

        # Verify stats exist
        stats = profiling_processor.get_performance_stats()
        assert stats['total_frames'] == 2

        # Reset
        profiling_processor.reset_stats()

        # Verify stats are cleared
        stats = profiling_processor.get_performance_stats()
        assert stats['total_frames'] == 0
        assert stats['avg_time_ms'] == 0.0


class TestOptimizedFrameProcessor:
    """Tests for OptimizedFrameProcessor class"""

    @pytest.fixture
    def processor(self):
        """Create optimized FrameProcessor instance"""
        return OptimizedFrameProcessor(validate_dimensions=True, profile=False)

    @pytest.fixture
    def profiling_processor(self):
        """Create optimized FrameProcessor with profiling enabled"""
        return OptimizedFrameProcessor(validate_dimensions=True, profile=True)

    @pytest.fixture
    def valid_png_bytes(self):
        """Create valid 1280x720 PNG bytes"""
        img = Image.new('RGB', (1280, 720), (100, 150, 200))
        buffer = BytesIO()
        img.save(buffer, format='PNG')
        return buffer.getvalue()

    def test_optimized_basic_conversion(self, processor, valid_png_bytes):
        """Test basic conversion with optimized processor"""
        rgba_bytes = processor.process(valid_png_bytes)

        assert isinstance(rgba_bytes, bytes)
        assert len(rgba_bytes) == 1280 * 720 * 4

    def test_optimized_multiple_frames(self, processor, valid_png_bytes):
        """Test that buffer reuse works correctly"""
        results = []
        for _ in range(10):
            rgba_bytes = processor.process(valid_png_bytes)
            results.append(rgba_bytes)

        # All results should be identical (same input)
        for result in results:
            assert len(result) == 1280 * 720 * 4
            assert result == results[0]

    def test_optimized_buffer_reuse(self, processor):
        """Test that buffer is reused across calls"""
        # Create different images
        img1 = Image.new('RGB', (1280, 720), (100, 150, 200))
        img2 = Image.new('RGB', (1280, 720), (200, 100, 50))

        buffer1 = BytesIO()
        img1.save(buffer1, format='PNG')
        png_bytes1 = buffer1.getvalue()

        buffer2 = BytesIO()
        img2.save(buffer2, format='PNG')
        png_bytes2 = buffer2.getvalue()

        # Process both
        rgba1 = processor.process(png_bytes1)
        rgba2 = processor.process(png_bytes2)

        # Results should be different
        assert rgba1 != rgba2

        # First pixel should be different
        assert rgba1[0:3] != rgba2[0:3]


class TestPerformanceBenchmarks:
    """Performance benchmark tests"""

    @pytest.fixture
    def valid_png_bytes(self):
        """Create valid 1280x720 PNG bytes"""
        img = Image.new('RGB', (1280, 720), (100, 150, 200))
        buffer = BytesIO()
        img.save(buffer, format='PNG')
        return buffer.getvalue()

    def test_conversion_time_standard(self, valid_png_bytes):
        """Benchmark standard processor conversion time"""
        processor = FrameProcessor(validate_dimensions=True, profile=True)

        # Warm up
        for _ in range(5):
            processor.process(valid_png_bytes)

        processor.reset_stats()

        # Benchmark 100 frames
        start_time = time.perf_counter()
        for _ in range(100):
            processor.process(valid_png_bytes)
        elapsed_time = time.perf_counter() - start_time

        avg_time_ms = (elapsed_time / 100) * 1000
        stats = processor.get_performance_stats()

        print(f"\nStandard Processor Benchmark:")
        print(f"  Total frames: {stats['total_frames']}")
        print(f"  Average time: {avg_time_ms:.2f}ms")
        print(f"  Min time: {stats['min_time_ms']:.2f}ms")
        print(f"  Max time: {stats['max_time_ms']:.2f}ms")
        print(f"  P95 time: {stats['p95_time_ms']:.2f}ms")

        # Assert performance target (<10ms)
        assert stats['avg_time_ms'] < 10.0, \
            f"Average conversion time {stats['avg_time_ms']:.2f}ms exceeds 10ms target"

    def test_conversion_time_optimized(self, valid_png_bytes):
        """Benchmark optimized processor conversion time"""
        processor = OptimizedFrameProcessor(validate_dimensions=True, profile=True)

        # Warm up
        for _ in range(5):
            processor.process(valid_png_bytes)

        processor.reset_stats()

        # Benchmark 100 frames
        start_time = time.perf_counter()
        for _ in range(100):
            processor.process(valid_png_bytes)
        elapsed_time = time.perf_counter() - start_time

        avg_time_ms = (elapsed_time / 100) * 1000
        stats = processor.get_performance_stats()

        print(f"\nOptimized Processor Benchmark:")
        print(f"  Total frames: {stats['total_frames']}")
        print(f"  Average time: {avg_time_ms:.2f}ms")
        print(f"  Min time: {stats['min_time_ms']:.2f}ms")
        print(f"  Max time: {stats['max_time_ms']:.2f}ms")
        print(f"  P95 time: {stats['p95_time_ms']:.2f}ms")

        # Assert performance target (<10ms)
        assert stats['avg_time_ms'] < 10.0, \
            f"Average conversion time {stats['avg_time_ms']:.2f}ms exceeds 10ms target"

    def test_performance_comparison(self, valid_png_bytes):
        """Compare standard vs optimized processor performance"""
        standard = FrameProcessor(validate_dimensions=True, profile=True)
        optimized = OptimizedFrameProcessor(validate_dimensions=True, profile=True)

        # Warm up both
        for _ in range(5):
            standard.process(valid_png_bytes)
            optimized.process(valid_png_bytes)

        standard.reset_stats()
        optimized.reset_stats()

        # Benchmark both (100 frames each)
        for _ in range(100):
            standard.process(valid_png_bytes)

        for _ in range(100):
            optimized.process(valid_png_bytes)

        standard_stats = standard.get_performance_stats()
        optimized_stats = optimized.get_performance_stats()

        print(f"\nPerformance Comparison:")
        print(f"  Standard avg: {standard_stats['avg_time_ms']:.2f}ms")
        print(f"  Optimized avg: {optimized_stats['avg_time_ms']:.2f}ms")
        print(f"  Improvement: {((standard_stats['avg_time_ms'] - optimized_stats['avg_time_ms']) / standard_stats['avg_time_ms'] * 100):.1f}%")

        # Both should meet target
        assert standard_stats['avg_time_ms'] < 10.0
        assert optimized_stats['avg_time_ms'] < 10.0


class TestEdgeCases:
    """Test edge cases and error conditions"""

    @pytest.fixture
    def processor(self):
        return FrameProcessor(validate_dimensions=True, profile=False)

    def test_grayscale_png(self, processor):
        """Test conversion of grayscale PNG"""
        img = Image.new('L', (1280, 720), 128)  # Grayscale
        buffer = BytesIO()
        img.save(buffer, format='PNG')
        png_bytes = buffer.getvalue()

        rgba_bytes = processor.process(png_bytes)

        # Should still work (PIL will convert L -> RGBA)
        assert len(rgba_bytes) == 1280 * 720 * 4

    def test_palette_png(self, processor):
        """Test conversion of palette-mode PNG"""
        img = Image.new('P', (1280, 720))  # Palette mode
        buffer = BytesIO()
        img.save(buffer, format='PNG')
        png_bytes = buffer.getvalue()

        rgba_bytes = processor.process(png_bytes)

        # Should work (PIL will convert P -> RGBA)
        assert len(rgba_bytes) == 1280 * 720 * 4

    def test_very_large_png_bytes(self, processor):
        """Test that processing doesn't leak memory with large inputs"""
        # Create a PNG and process it multiple times
        img = Image.new('RGB', (1280, 720), (100, 150, 200))
        buffer = BytesIO()
        img.save(buffer, format='PNG')
        png_bytes = buffer.getvalue()

        # Process many frames (would reveal memory leaks)
        for _ in range(50):
            rgba_bytes = processor.process(png_bytes)
            assert len(rgba_bytes) == 1280 * 720 * 4
