import os
import shutil
import pytest
from django.conf import settings

@pytest.fixture(scope="session", autouse=True)
def cleanup_test_media():
    """
    Session-scoped fixture to automatically clean up temporary media files
    generated during the test run.
    """
    yield
    # Clean up settings.MEDIA_ROOT
    media_root = getattr(settings, "MEDIA_ROOT", None)
    if media_root and os.path.exists(media_root) and "media_test" in media_root:
        shutil.rmtree(media_root, ignore_errors=True)

    # Also clean up any legacy directories created due to missing trailing slash
    base_dir = getattr(settings, "BASE_DIR", None)
    if base_dir:
        legacy_dir = os.path.join(base_dir, "media_testlongs")
        if os.path.exists(legacy_dir):
            shutil.rmtree(legacy_dir, ignore_errors=True)
