"""
Test script to verify write access to image directories
"""
import os
import sys
from pathlib import Path

# Add project to path
sys.path.insert(0, str(Path(__file__).parent))

# Test write access logic
def test_write_access():
    print("=" * 60)
    print("Testing Image Directory Write Access")
    print("=" * 60)
    
    # Test 1: Absolute path /data/app/images
    images_dir = '/data/app/images'
    write_test_passed = False
    
    print(f"\n[Test 1] Testing absolute path: {images_dir}")
    try:
        os.makedirs(images_dir, exist_ok=True)
        print(f"  ✓ Directory created/verified: {images_dir}")
        
        # Test write access
        test_file = os.path.join(images_dir, '.write_test')
        print(f"  → Attempting to write test file: {test_file}")
        
        with open(test_file, 'w') as f:
            f.write('test')
        print(f"  ✓ Write successful")
        
        os.remove(test_file)
        print(f"  ✓ Test file removed")
        
        write_test_passed = True
        print(f"  ✅ SUCCESS: {images_dir} is writable")
        
    except PermissionError as e:
        print(f"  ✗ PERMISSION DENIED: {e}")
        print(f"  → Trying fallback path...")
        
        # Fallback to project-relative path
        try:
            from django.conf import settings
            base_dir = Path(settings.BASE_DIR) if hasattr(settings, 'BASE_DIR') else Path(__file__).resolve().parent.parent
        except:
            base_dir = Path(__file__).resolve().parent
        
        images_dir = str(base_dir / 'data' / 'app' / 'images')
        print(f"\n[Test 2] Testing fallback path: {images_dir}")
        
        try:
            os.makedirs(images_dir, exist_ok=True)
            print(f"  ✓ Directory created/verified: {images_dir}")
            
            # Test fallback directory write access
            test_file = os.path.join(images_dir, '.write_test')
            print(f"  → Attempting to write test file: {test_file}")
            
            with open(test_file, 'w') as f:
                f.write('test')
            print(f"  ✓ Write successful")
            
            os.remove(test_file)
            print(f"  ✓ Test file removed")
            
            write_test_passed = True
            print(f"  ✅ SUCCESS: {images_dir} is writable")
            
        except Exception as fallback_error:
            print(f"  ✗ FAILED: {fallback_error}")
            print(f"  ❌ ERROR: Neither /data/app/images nor {images_dir} is writable")
            return False
            
    except Exception as e:
        print(f"  ✗ ERROR: {e}")
        print(f"  → Trying fallback path...")
        
        # Fallback to project-relative path
        try:
            from django.conf import settings
            base_dir = Path(settings.BASE_DIR) if hasattr(settings, 'BASE_DIR') else Path(__file__).resolve().parent.parent
        except:
            base_dir = Path(__file__).resolve().parent
        
        images_dir = str(base_dir / 'data' / 'app' / 'images')
        print(f"\n[Test 2] Testing fallback path: {images_dir}")
        
        try:
            os.makedirs(images_dir, exist_ok=True)
            print(f"  ✓ Directory created/verified: {images_dir}")
            
            # Test fallback directory write access
            test_file = os.path.join(images_dir, '.write_test')
            print(f"  → Attempting to write test file: {test_file}")
            
            with open(test_file, 'w') as f:
                f.write('test')
            print(f"  ✓ Write successful")
            
            os.remove(test_file)
            print(f"  ✓ Test file removed")
            
            write_test_passed = True
            print(f"  ✅ SUCCESS: {images_dir} is writable")
            
        except Exception as fallback_error:
            print(f"  ✗ FAILED: {fallback_error}")
            print(f"  ❌ ERROR: Neither /data/app/images nor {images_dir} is writable")
            return False
    
    if not write_test_passed:
        print(f"\n❌ FAILED: No writable directory found")
        return False
    
    print(f"\n" + "=" * 60)
    print(f"✅ FINAL RESULT: Images will be saved to: {images_dir}")
    print("=" * 60)
    return True

if __name__ == '__main__':
    success = test_write_access()
    sys.exit(0 if success else 1)

