import bpy
import os
import re

def relocate_libraries():
    """
    Relocate linked library files from Synology Drive to NAS storage.
    Changes paths from C:\\Users\\Nathan\\SynologyDrive\\ to R:\\
    """
    
    # Define the path mappings
    old_base = r"C:\Users\Nathan\SynologyDrive"
    new_base = r"R:"
    
    # Track changes
    changed_files = []
    failed_files = []
    
    print("=== Library Relocation Script ===")
    print(f"Mapping: {old_base} → {new_base}")
    print()
    
    # Process all library files
    for lib in bpy.data.libraries:
        if lib.filepath:
            old_path = lib.filepath
            
            # Check if this is a Synology Drive path
            if old_base in old_path:
                # Create new path
                new_path = old_path.replace(old_base, new_base)
                
                # Verify the new file exists
                if os.path.exists(new_path):
                    try:
                        # Update the library path
                        lib.filepath = new_path
                        changed_files.append((old_path, new_path))
                        print(f"✓ Relocated: {os.path.basename(old_path)}")
                        print(f"  {old_path}")
                        print(f"  → {new_path}")
                        print()
                    except Exception as e:
                        failed_files.append((old_path, str(e)))
                        print(f"✗ Failed to relocate: {os.path.basename(old_path)}")
                        print(f"  Error: {e}")
                        print()
                else:
                    failed_files.append((old_path, "Target file not found"))
                    print(f"✗ Target not found: {new_path}")
                    print()
            else:
                print(f"ℹ Skipped (not Synology Drive): {old_path}")
                print()
    
    # Summary
    print("=== Summary ===")
    print(f"Successfully relocated: {len(changed_files)} files")
    print(f"Failed to relocate: {len(failed_files)} files")
    
    if changed_files:
        print("\nRelocated files:")
        for old, new in changed_files:
            print(f"  {os.path.basename(old)}")
    
    if failed_files:
        print("\nFailed files:")
        for old, reason in failed_files:
            print(f"  {os.path.basename(old)}: {reason}")
    
    return len(changed_files), len(failed_files)

# Run the script
if __name__ == "__main__":
    success_count, fail_count = relocate_libraries()
    
    if success_count > 0:
        print(f"\n✅ Successfully relocated {success_count} library files!")
        print("You may need to save your .blend file to preserve these changes.")
    
    if fail_count > 0:
        print(f"\n⚠️  {fail_count} files failed to relocate.")
        print("Check that the NAS paths exist and are accessible.") 