#!/usr/bin/env python3
"""
Cross-platform test script for persistent directory functionality
Tests MbetterClient directory creation on Windows, macOS, and Linux
"""

import sys
import platform
from pathlib import Path

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

from mbetterclient.config.settings import get_user_data_dir, get_user_config_dir, get_user_cache_dir, is_pyinstaller_executable

def test_directory_creation():
    """Test directory creation and permissions across platforms"""
    print("=" * 60)
    print(f"MbetterClient Cross-Platform Directory Test")
    print("=" * 60)
    print(f"Platform: {platform.system()} {platform.release()}")
    print(f"Python: {sys.version}")
    print(f"PyInstaller mode: {is_pyinstaller_executable()}")
    print()
    
    # Test each directory type
    directories = {
        "Data Directory": get_user_data_dir,
        "Config Directory": get_user_config_dir,
        "Cache Directory": get_user_cache_dir
    }
    
    results = {}
    
    for dir_name, dir_func in directories.items():
        print(f"Testing {dir_name}...")
        
        try:
            # Get directory path
            dir_path = dir_func()
            print(f"  Path: {dir_path}")
            
            # Check if directory exists
            if dir_path.exists():
                print(f"  ✅ Directory exists")
            else:
                print(f"  ❌ Directory does not exist")
                continue
            
            # Check if directory is writable
            test_file = dir_path / f'.test_write_{dir_name.lower().replace(" ", "_")}'
            try:
                test_file.write_text('MbetterClient test file')
                test_file.unlink()
                print(f"  ✅ Directory is writable")
                writable = True
            except (OSError, PermissionError) as e:
                print(f"  ❌ Directory not writable: {e}")
                writable = False
            
            # Test subdirectory creation
            test_subdir = dir_path / 'test_subdir'
            try:
                test_subdir.mkdir(exist_ok=True)
                test_subdir.rmdir()
                print(f"  ✅ Can create subdirectories")
                can_create_subdirs = True
            except (OSError, PermissionError) as e:
                print(f"  ❌ Cannot create subdirectories: {e}")
                can_create_subdirs = False
            
            results[dir_name] = {
                'path': str(dir_path),
                'exists': dir_path.exists(),
                'writable': writable,
                'can_create_subdirs': can_create_subdirs
            }
            
        except Exception as e:
            print(f"  ❌ Error testing {dir_name}: {e}")
            results[dir_name] = {
                'path': 'ERROR',
                'exists': False,
                'writable': False,
                'can_create_subdirs': False,
                'error': str(e)
            }
        
        print()
    
    return results

def test_database_path():
    """Test database path resolution"""
    print("Testing Database Path Resolution...")
    
    try:
        from mbetterclient.config.settings import DatabaseConfig
        
        # Test default database config
        db_config = DatabaseConfig()
        db_path = db_config.get_absolute_path()
        
        print(f"  Database path: {db_path}")
        print(f"  Parent directory: {db_path.parent}")
        print(f"  Parent exists: {db_path.parent.exists()}")
        
        # Try to create parent directory
        try:
            db_path.parent.mkdir(parents=True, exist_ok=True)
            print(f"  ✅ Can create database parent directory")
        except Exception as e:
            print(f"  ❌ Cannot create database parent directory: {e}")
        
        return str(db_path)
        
    except Exception as e:
        print(f"  ❌ Error testing database path: {e}")
        return None

def test_application_directories():
    """Test actual application directory structure"""
    print("Testing Application Directory Structure...")
    
    try:
        from mbetterclient.config.settings import AppSettings
        
        settings = AppSettings()
        settings.ensure_directories()
        
        # Check directories that should be created
        data_dir = get_user_data_dir()
        config_dir = get_user_config_dir()
        
        required_dirs = [
            data_dir / "logs",
            data_dir / "data", 
            data_dir / "uploads",
            config_dir / "templates"
        ]
        
        all_good = True
        for req_dir in required_dirs:
            if req_dir.exists():
                print(f"  ✅ {req_dir}")
            else:
                print(f"  ❌ Missing: {req_dir}")
                all_good = False
        
        return all_good
        
    except Exception as e:
        print(f"  ❌ Error testing application directories: {e}")
        return False

def main():
    """Main test function"""
    print("Starting MbetterClient cross-platform directory tests...")
    print()
    
    # Test basic directory creation
    dir_results = test_directory_creation()
    
    # Test database path
    db_path = test_database_path()
    print()
    
    # Test application directory structure
    app_dirs_ok = test_application_directories()
    print()
    
    # Summary
    print("=" * 60)
    print("TEST SUMMARY")
    print("=" * 60)
    
    all_tests_passed = True
    
    for dir_name, result in dir_results.items():
        status = "✅ PASS" if (result['exists'] and result['writable'] and result['can_create_subdirs']) else "❌ FAIL"
        print(f"{dir_name}: {status}")
        if 'error' in result:
            print(f"  Error: {result['error']}")
        else:
            print(f"  Path: {result['path']}")
        
        if status == "❌ FAIL":
            all_tests_passed = False
    
    print()
    print(f"Database Path: {'✅ OK' if db_path else '❌ ERROR'}")
    if db_path:
        print(f"  {db_path}")
    
    print(f"Application Structure: {'✅ OK' if app_dirs_ok else '❌ ERROR'}")
    
    print()
    if all_tests_passed and db_path and app_dirs_ok:
        print("🎉 ALL TESTS PASSED - Cross-platform persistence ready!")
        return 0
    else:
        print("⚠️  SOME TESTS FAILED - Check errors above")
        return 1

if __name__ == "__main__":
    sys.exit(main())