"""
Pytest configuration and fixtures for StarPunk tests
"""

import pytest
import tempfile
from pathlib import Path
from starpunk import create_app


@pytest.fixture
def app():
    """Create test Flask application"""
    # Create temporary directory for test data
    temp_dir = tempfile.mkdtemp()
    temp_path = Path(temp_dir)

    # Test configuration
    config = {
        "TESTING": True,
        "DEBUG": False,
        "DATA_PATH": temp_path,
        "NOTES_PATH": temp_path / "notes",
        "DATABASE_PATH": temp_path / "test.db",
        "SESSION_SECRET": "test-secret-key",
        "ADMIN_ME": "https://test.example.com",
        "SITE_URL": "http://localhost:5000",
    }

    # Create app with test config
    app = create_app(config)

    yield app

    # Cleanup (optional - temp dir will be cleaned up by OS)


@pytest.fixture
def client(app):
    """Create test client"""
    return app.test_client()


@pytest.fixture
def runner(app):
    """Create test CLI runner"""
    return app.test_cli_runner()


@pytest.fixture
def data_dir(app):
    """Return test data directory path"""
    return app.config['DATA_PATH']


@pytest.fixture
def sample_note(app):
    """Create a single sample note for testing"""
    from starpunk.notes import create_note

    with app.app_context():
        note = create_note(
            content="This is a sample note for testing.\n\nIt has multiple paragraphs.",
            published=True,
        )
        return note


@pytest.fixture
def published_note_with_tags(app):
    """Create a published note with tags for microformats testing (v1.3.0)"""
    from starpunk.notes import create_note

    with app.app_context():
        note = create_note(
            content="Test note with tags for microformats validation",
            published=True,
            tags=["Python", "IndieWeb", "Testing"]
        )
        return note


@pytest.fixture
def published_note_with_media(app):
    """Create a published note with media for u-photo testing (v1.3.0)"""
    from starpunk.notes import create_note
    from starpunk.media import save_media, attach_media_to_note
    from PIL import Image
    import io

    with app.app_context():
        note = create_note(content="Test note with media", published=True)

        # Create minimal valid JPEG for testing
        img = Image.new('RGB', (100, 100), color='red')
        img_bytes = io.BytesIO()
        img.save(img_bytes, format='JPEG')
        img_bytes.seek(0)

        # Save media and attach to note
        media_info = save_media(img_bytes.getvalue(), 'test.jpg')
        attach_media_to_note(note.id, [media_info['id']], ['Test image'])

        return note
