#!/usr/bin/env python3
"""
Test that images render correctly in EPUB files.

This test verifies that:
1. All images in the EPUB are loaded with correct dimensions
2. Images can be navigated to without errors
3. Pages with images render successfully
4. The rendered pages contain actual image content (not blank)
"""

import pytest
from dreader.application import EbookReader
from pyWebLayout.abstract.block import Image as AbstractImage
from PIL import Image
import numpy as np


def test_epub_images():
    """Test that EPUB images render correctly."""

    # Create reader
    reader = EbookReader(page_size=(800, 1200))

    # Load EPUB
    epub_path = "tests/data/library-epub/pg11-images-3.epub"
    success = reader.load_epub(epub_path)

    assert success, "Failed to load EPUB"
    assert reader.book_title == "Alice's Adventures in Wonderland"

    # Check that images were parsed
    images = [b for b in reader.blocks if isinstance(b, AbstractImage)]
    assert len(images) >= 1, f"Expected at least 1 image, found {len(images)}"

    # Check that all images have dimensions set
    for img in images:
        assert img.width is not None, f"Image {img.source} has no width"
        assert img.height is not None, f"Image {img.source} has no height"
        assert img.width > 0, f"Image {img.source} has invalid width: {img.width}"
        assert img.height > 0, f"Image {img.source} has invalid height: {img.height}"

        # Check that image is loaded into memory
        assert hasattr(img, '_loaded_image'), f"Image {img.source} not loaded"
        assert img._loaded_image is not None, f"Image {img.source} _loaded_image is None"

    # Test navigation through first 15 pages (which should include all images)
    for page_num in range(15):
        page_img = reader.get_current_page()

        assert page_img is not None, f"Page {page_num + 1} failed to render"
        assert isinstance(page_img, Image.Image), f"Page {page_num + 1} is not a PIL Image"
        assert page_img.size == (800, 1200), f"Page {page_num + 1} has wrong size: {page_img.size}"

        # Check that page has some non-white content
        arr = np.array(page_img.convert('RGB'))
        non_white_pixels = np.sum(arr < 255)

        assert non_white_pixels > 100, f"Page {page_num + 1} appears to be blank (only {non_white_pixels} non-white pixels)"

        # Navigate to next page
        if page_num < 14:
            next_result = reader.next_page()
            if next_result is None:
                # It's OK to reach end of book early
                break


def test_cover_image():
    """Specifically test that the cover image renders."""

    reader = EbookReader(page_size=(800, 1200))
    reader.load_epub("tests/data/library-epub/pg11-images-3.epub")

    # The first page should have the cover image
    page_img = reader.get_current_page()
    assert page_img is not None, "Cover page failed to render"

    # Save for visual inspection
    output_path = "/tmp/epub_cover_test.png"
    page_img.save(output_path)

    # Check that it has significant content (the cover image)
    arr = np.array(page_img.convert('RGB'))
    non_white_pixels = np.sum(arr < 255)

    # The cover page should have substantial content
    assert non_white_pixels > 10000, f"Cover page has too few non-white pixels: {non_white_pixels}"


def test_multiple_epub_images():
    """Test images across multiple EPUB files."""

    epub_files = [
        ("tests/data/library-epub/pg11-images-3.epub", "Alice's Adventures in Wonderland"),
        ("tests/data/library-epub/pg16328-images-3.epub", "Beowulf: An Anglo-Saxon Epic Poem"),
        ("tests/data/library-epub/pg5200-images-3.epub", "Metamorphosis"),
    ]

    for epub_path, expected_title in epub_files:
        reader = EbookReader(page_size=(800, 1200))
        success = reader.load_epub(epub_path)

        assert success, f"Failed to load {epub_path}"
        assert reader.book_title == expected_title

        # Check that at least one image exists
        images = [b for b in reader.blocks if isinstance(b, AbstractImage)]
        assert len(images) >= 1, f"{epub_path} should have at least 1 image"

        # Check first image is valid
        img = images[0]
        assert img.width > 0 and img.height > 0, f"Invalid dimensions in {epub_path}"


if __name__ == "__main__":
    # Run tests directly
    print("Testing EPUB images...")

    print("\n1. Testing all images load and render...")
    test_epub_images()
    print("✓ PASSED")

    print("\n2. Testing cover image...")
    test_cover_image()
    print("✓ PASSED")

    print("\n3. Testing multiple EPUB images...")
    test_multiple_epub_images()
    print("✓ PASSED")

    print("\n✓ All tests passed!")
