#!/usr/bin/env python3
"""
Debug script to test if asset files are being deleted during video creation.
"""
import os
import sys
import django
from pathlib import Path

# Add the project root to Python path
PROJECT_ROOT = Path(__file__).parent
sys.path.insert(0, str(PROJECT_ROOT))

# Set Django settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tests.settings_test')

# Setup Django
django.setup()

from endoreg_db.models import VideoFile
from tests.media.video.helper import get_random_video_path_by_examination_alias
from tests.helpers.default_objects import DEFAULT_CENTER_NAME, DEFAULT_ENDOSCOPY_PROCESSOR_NAME
from tests.helpers.data_loader import load_base_db_data
from django.conf import settings

def check_asset_deletion():
    """Test if asset files are deleted during video creation."""
    
    print("DEBUG: Checking asset deletion...")
    
    # Load base database data
    load_base_db_data()
    
    # Get initial asset files
    asset_dir = settings.ASSET_DIR
    print(f"ASSET_DIR: {asset_dir}")
    
    initial_files = list(asset_dir.glob("*.mp4"))
    print(f"Initial video assets: {[f.name for f in initial_files]}")
    
    if not initial_files:
        print("ERROR: No video assets found!")
        return
    
    # Test video creation with delete_source=False (should be safe)
    try:
        video_path = get_random_video_path_by_examination_alias(
            examination_alias='egd', is_anonymous=False
        )
        print(f"Selected video path: {video_path}")
        print(f"File exists before: {video_path.exists()}")
        
        # Create video with delete_source=False (should be safe!)
        video_file = VideoFile.create_from_file(
            file_path=video_path,
            center_name=DEFAULT_CENTER_NAME,
            processor_name=DEFAULT_ENDOSCOPY_PROCESSOR_NAME, 
            delete_source=False  # CRITICAL: Should NOT delete source!
        )
        
        if video_file:
            print(f"Video created: {video_file.uuid}")
            print(f"File exists after creation: {video_path.exists()}")
            
            # Check asset files after creation
            final_files = list(asset_dir.glob("*.mp4"))
            print(f"Final video assets: {[f.name for f in final_files]}")
            
            missing_files = set(f.name for f in initial_files) - set(f.name for f in final_files)
            if missing_files:
                print(f"ERROR: Asset files deleted during test: {missing_files}")
            else:
                print("SUCCESS: No asset files were deleted")
                
            # Cleanup the created video
            video_file.delete_with_file()
        else:
            print("ERROR: Video file creation returned None")
            print(f"File exists after failed creation: {video_path.exists()}")
        
    except Exception as e:
        print(f"ERROR during test: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    check_asset_deletion()
