#!/usr/bin/env python3
"""
Unit Tests for ScreenshotCapture

Tests browser lifecycle, page loading, screenshot capture, and error handling.
"""

import asyncio
import pytest
import os
from pathlib import Path

# Import the module to test
import sys
sys.path.insert(0, str(Path(__file__).parent.parent))
from screenshot_capture import ScreenshotCapture


# Get path to test fixture
TEST_DECK_PATH = Path(__file__).parent / "fixtures" / "test_deck.html"
TEST_DECK_URL = f"file://{TEST_DECK_PATH.absolute()}"


class TestScreenshotCapture:
    """Test suite for ScreenshotCapture class"""

    @pytest.mark.asyncio
    async def test_browser_launch_close_cycle(self):
        """Test that browser can be launched and closed properly"""
        capture = ScreenshotCapture(TEST_DECK_URL)

        # Initially not ready
        assert not capture.is_ready, "Should not be ready before start()"

        # Start browser
        await capture.start()

        # Should be ready after start
        assert capture.is_ready, "Should be ready after start()"

        # Stop browser
        await capture.stop()

        # Should not be ready after stop
        assert not capture.is_ready, "Should not be ready after stop()"

    @pytest.mark.asyncio
    async def test_page_loading_with_local_file(self):
        """Test that local HTML file can be loaded successfully"""
        capture = ScreenshotCapture(TEST_DECK_URL)

        # Verify test file exists
        assert TEST_DECK_PATH.exists(), f"Test deck not found: {TEST_DECK_PATH}"

        # Start and load page
        await capture.start()

        try:
            # Should be ready without errors
            assert capture.is_ready

            # Page should be loaded (internal state check)
            assert capture._page is not None

        finally:
            await capture.stop()

    @pytest.mark.asyncio
    async def test_screenshot_returns_png_bytes(self):
        """Test that screenshot returns valid PNG bytes"""
        capture = ScreenshotCapture(TEST_DECK_URL)

        await capture.start()

        try:
            # Capture screenshot
            png_bytes = await capture.capture_frame()

            # Verify it's bytes
            assert isinstance(png_bytes, bytes), "Should return bytes"

            # Verify it's not empty
            assert len(png_bytes) > 0, "Should not be empty"

            # Verify PNG magic number (first 8 bytes)
            # PNG signature: 89 50 4E 47 0D 0A 1A 0A
            assert png_bytes[:8] == b'\x89PNG\r\n\x1a\n', "Should have valid PNG signature"

            # Verify reasonable size for 1280x720 image
            # Should be between 10KB and 500KB for typical screenshots
            assert 10_000 < len(png_bytes) < 500_000, \
                f"PNG size ({len(png_bytes)} bytes) outside expected range"

        finally:
            await capture.stop()

    @pytest.mark.asyncio
    async def test_multiple_captures(self):
        """Test that multiple screenshots can be captured in sequence"""
        capture = ScreenshotCapture(TEST_DECK_URL)

        await capture.start()

        try:
            # Capture multiple frames
            frames = []
            for i in range(5):
                frame = await capture.capture_frame()
                frames.append(frame)

            # All frames should be valid
            assert len(frames) == 5

            # All should be PNG bytes
            for frame in frames:
                assert isinstance(frame, bytes)
                assert frame[:8] == b'\x89PNG\r\n\x1a\n'

        finally:
            await capture.stop()

    @pytest.mark.asyncio
    async def test_capture_before_start_raises_error(self):
        """Test that capturing before start() raises RuntimeError"""
        capture = ScreenshotCapture(TEST_DECK_URL)

        # Should raise error if not started
        with pytest.raises(RuntimeError, match="Browser not started"):
            await capture.capture_frame()

    @pytest.mark.asyncio
    async def test_metrics_tracking(self):
        """Test that performance metrics are tracked correctly"""
        capture = ScreenshotCapture(TEST_DECK_URL)

        await capture.start()

        try:
            # Initial metrics should be zero
            metrics = capture.metrics
            assert metrics["capture_count"] == 0
            assert metrics["avg_capture_time_ms"] == 0.0
            assert metrics["failed_captures"] == 0

            # Capture some frames
            for i in range(3):
                await capture.capture_frame()

            # Metrics should be updated
            metrics = capture.metrics
            assert metrics["capture_count"] == 3
            assert metrics["avg_capture_time_ms"] > 0
            assert metrics["failed_captures"] == 0
            assert metrics["success_rate"] == 100.0

        finally:
            await capture.stop()

    @pytest.mark.asyncio
    async def test_restart_functionality(self):
        """Test that browser can be restarted"""
        capture = ScreenshotCapture(TEST_DECK_URL)

        # Start, capture, stop
        await capture.start()
        frame1 = await capture.capture_frame()
        await capture.stop()

        assert not capture.is_ready

        # Restart using restart() method
        await capture.start()
        assert capture.is_ready
        frame2 = await capture.capture_frame()
        await capture.stop()

        # Both frames should be valid
        assert isinstance(frame1, bytes)
        assert isinstance(frame2, bytes)

    @pytest.mark.asyncio
    async def test_capture_performance(self):
        """Test that capture time meets performance targets (<80ms average)"""
        capture = ScreenshotCapture(TEST_DECK_URL)

        await capture.start()

        try:
            # Capture several frames to get average
            num_captures = 10
            for i in range(num_captures):
                await capture.capture_frame()

            # Check metrics
            metrics = capture.metrics
            avg_time = metrics["avg_capture_time_ms"]

            # Log the performance
            print(f"\nCapture performance: {avg_time:.1f}ms average over {num_captures} captures")

            # Warn if exceeds target (but don't fail test - hardware dependent)
            if avg_time > 80:
                print(f"WARNING: Average capture time ({avg_time:.1f}ms) exceeds 80ms target")

            # Should complete in reasonable time (< 200ms even on slow hardware)
            assert avg_time < 200, f"Capture time ({avg_time}ms) is too slow"

        finally:
            await capture.stop()

    @pytest.mark.asyncio
    async def test_invalid_url_handling(self):
        """Test that invalid URLs are handled gracefully"""
        capture = ScreenshotCapture("https://this-domain-does-not-exist-12345.com/page")

        # Should raise exception during start (page load failure)
        with pytest.raises(Exception):
            await capture.start()

        # Cleanup should still work
        await capture.stop()

    @pytest.mark.asyncio
    async def test_double_stop_is_safe(self):
        """Test that calling stop() multiple times is safe"""
        capture = ScreenshotCapture(TEST_DECK_URL)

        await capture.start()
        await capture.stop()

        # Calling stop again should not raise error
        await capture.stop()
        await capture.stop()

        assert not capture.is_ready


class TestScreenshotCaptureIntegration:
    """Integration tests simulating real usage patterns"""

    @pytest.mark.asyncio
    async def test_continuous_capture_simulation(self):
        """Simulate continuous capture like in production (10 FPS for 2 seconds)"""
        capture = ScreenshotCapture(TEST_DECK_URL)

        await capture.start()

        try:
            frame_count = 0
            target_frames = 20  # 2 seconds at 10 FPS
            frame_interval = 0.1  # 100ms = 10 FPS

            for i in range(target_frames):
                frame = await capture.capture_frame()
                frame_count += 1

                assert isinstance(frame, bytes)
                assert len(frame) > 0

                # Simulate frame interval
                await asyncio.sleep(frame_interval)

            assert frame_count == target_frames

            # Check performance
            metrics = capture.metrics
            print(f"\nContinuous capture: {metrics['capture_count']} frames, "
                  f"{metrics['avg_capture_time_ms']:.1f}ms avg")

        finally:
            await capture.stop()

    @pytest.mark.asyncio
    async def test_error_recovery_simulation(self):
        """Test recovery from errors using restart()"""
        capture = ScreenshotCapture(TEST_DECK_URL)

        # Initial start
        await capture.start()

        try:
            # Capture some frames
            frame1 = await capture.capture_frame()
            assert frame1

            # Simulate error by manually closing browser (forcing restart scenario)
            await capture.stop()

            # Restart and continue
            await capture.start()
            frame2 = await capture.capture_frame()
            assert frame2

        finally:
            await capture.stop()


# Test configuration
@pytest.fixture(scope="session", autouse=True)
def check_test_deck_exists():
    """Ensure test deck HTML file exists before running tests"""
    if not TEST_DECK_PATH.exists():
        pytest.exit(f"Test deck not found: {TEST_DECK_PATH}")


if __name__ == "__main__":
    # Allow running tests directly
    pytest.main([__file__, "-v", "-s"])
