import pytest
import tempfile
import time
import os
from pathlib import Path
import subprocess
import sys


def test_python_version():
    """Test that Python 3.9+ is available."""
    version = sys.version_info
    assert version.major >= 3
    assert version.minor >= 9


def test_required_modules():
    """Test that required Python modules are installed."""
    try:
        import jinja2  # noqa: F401
        import yaml  # noqa: F401
    except ImportError as e:
        pytest.fail(f"Required module not found: {e}")


def test_imagemagick_available():
    """Test that ImageMagick is installed and accessible."""
    try:
        result = subprocess.run(['convert', '-version'], capture_output=True, text=True, timeout=10)
        assert result.returncode == 0
        assert 'ImageMagick' in result.stdout
    except (subprocess.TimeoutExpired, FileNotFoundError):
        pytest.fail("ImageMagick not available or not working")


def test_format_file_size():
    # Add current directory to path instead of /src
    sys.path.insert(0, '.')
    from gallery import format_file_size
    assert format_file_size(0) == "0 B"
    assert format_file_size(1024) == "1.0 KB"
    assert format_file_size(1048576) == "1.0 MB"
    assert format_file_size(1073741824) == "1.0 GB"


def test_needs_update():
    sys.path.insert(0, '.')
    from gallery import needs_update
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        source = temp_path / "source.txt"
        target = temp_path / "target.txt"
        source.write_text("test")
        assert needs_update(source, target)
        target.write_text("test")
        time.sleep(0.1)
        os.utime(target, (time.time(), time.time()))
        assert not needs_update(source, target)


def test_metadata_loading():
    sys.path.insert(0, '.')
    from utils.metadata import load_metadata_file
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        yaml_file = temp_path / "test.yaml"
        yaml_content = "title: Test\nauthor: Container Test\n"
        yaml_file.write_text(yaml_content)
        metadata = load_metadata_file(yaml_file)
        assert metadata['title'] == 'Test'
        assert metadata['author'] == 'Container Test'


def test_metadata_inheritance():
    sys.path.insert(0, '.')
    from utils.metadata import merge_metadata
    parent = {'project': 'Test', 'version': '1.0'}
    child = {'experiment': 'A', 'version': '1.1'}
    merged = merge_metadata(parent, child)
    assert merged['project'] == 'Test'
    assert merged['experiment'] == 'A'
    assert merged['version'] == '1.1'


def create_mock_pdf(path: Path):
    path.write_text("%PDF-1.4\nMock PDF for testing")


def test_pdf_conversion(tmpdir):
    sys.path.insert(0, '/src')
    from gallery import convert_pdf_to_png, GalleryConfig
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        pdf_path = temp_path / "test.pdf"
        create_mock_pdf(pdf_path)
        try:
            convert_pdf_to_png(pdf_path, GalleryConfig(tmpdir))
            png_path = pdf_path.with_suffix('.png')
            assert png_path.exists()
        except subprocess.CalledProcessError:
            pytest.skip("Mock PDF not processable by ImageMagick")


def create_test_structure(source_dir):
    pdf_path = source_dir / "test_plot.pdf"
    pdf_path.write_text("%PDF-1.4\nTest plot content")
    metadata_path = source_dir / "metadata.yaml"
    metadata_path.write_text("title: Container Test\nauthor: CI Pipeline\n")


def test_build_gallery(tmpdir):
    sys.path.insert(0, '.')
    from gallery import build_gallery, GalleryConfig
    from unittest.mock import patch
    with tempfile.TemporaryDirectory() as temp_dir:
        temp_path = Path(temp_dir)
        source_dir = temp_path / "source"
        web_dir = temp_path / "web"
        source_dir.mkdir()
        web_dir.mkdir()
        create_test_structure(source_dir)
        
        # Mock the PDF conversion and create the expected PNG file
        def mock_convert_pdf_to_png(pdf_path):
            png_path = pdf_path.with_suffix('.png')
            png_path.write_text("Mock PNG content")
        
        with patch('gallery.convert_pdf_to_png', side_effect=mock_convert_pdf_to_png):
            try:
                build_gallery(GalleryConfig(tmpdir), source_dir=source_dir, web_dir=web_dir)
                html_file = web_dir / "index.html"
                assert html_file.exists()
                pdf_file = web_dir / "test_plot.pdf"
                assert pdf_file.exists()
                png_file = web_dir / "test_plot.png"
                assert png_file.exists()
            except Exception as e:
                pytest.skip(f"Gallery generation failed: {e}")
