import requests
import uuid

BASE_URL = 'http://127.0.0.1:5000'
NAMESPACE_CLOUDVAULT = uuid.UUID('6ba7b810-9dad-11d1-80b4-00c04fd430c8')

def test_multi_account_and_device_sync():
    print("==================================================")
    print("TESTING 1-MASTER-ID MULTI-DRIVE POOL & DEVICE SYNC")
    print("==================================================")

    # 1. Master Account Registration
    master_email = f"master_{uuid.uuid4().hex[:6]}@example.com"
    pwd = "masterpassword123"
    name = "Master User"

    reg_res = requests.post(f"{BASE_URL}/api/auth/register", json={
        'email': master_email,
        'password': pwd,
        'displayName': name,
        'deviceName': 'Phone 1 (Original Device)'
    })
    assert reg_res.status_code == 201, f"Reg failed: {reg_res.text}"
    user_id = reg_res.json()['user']['id']
    token1 = reg_res.json()['sessionToken']
    h1 = {'Authorization': f'Bearer {token1}', 'Content-Type': 'application/json'}
    print(f"✓ Master Account created: {master_email} (ID: {user_id})")

    # 2. Connect Google ID 1 (15 GB) on Phone 1
    g1_email = "g1_photos@gmail.com"
    expected_g1_id = str(uuid.uuid5(NAMESPACE_CLOUDVAULT, f"cloudvault:acc:{user_id}:{g1_email}"))

    acc1_res = requests.post(f"{BASE_URL}/api/drive/accounts", headers=h1, json={
        'email': g1_email,
        'displayName': 'G1 Photos (15GB)',
        'id': expected_g1_id
    })
    assert acc1_res.status_code == 201
    assert acc1_res.json()['account']['id'] == expected_g1_id
    print(f"✓ Connected Google ID 1: {g1_email} with deterministic ID: {expected_g1_id}")

    # 3. Connect Google ID 2 (15 GB) on Phone 1 -> Pool expands to 30 GB!
    g2_email = "g2_videos@gmail.com"
    expected_g2_id = str(uuid.uuid5(NAMESPACE_CLOUDVAULT, f"cloudvault:acc:{user_id}:{g2_email}"))

    acc2_res = requests.post(f"{BASE_URL}/api/drive/accounts", headers=h1, json={
        'email': g2_email,
        'displayName': 'G2 Videos (15GB)',
        'id': expected_g2_id
    })
    assert acc2_res.status_code == 201
    print(f"✓ Connected Google ID 2: {g2_email} with deterministic ID: {expected_g2_id}")

    # Verify Pool Quota is 30 GB (15 GB * 2)
    quota_res = requests.get(f"{BASE_URL}/api/storage/quota", headers=h1).json()
    assert len(quota_res['accountBreakdown']) == 2
    assert quota_res['totalQuota'] == 16106127360 * 2
    print(f"✓ Unified Multi-Drive Pool verified: {quota_res['totalQuota'] / (1024**3):.1f} GB total storage across 2 drives")

    # 4. Upload files to Drive 1 and Drive 2
    sync_res = requests.post(f"{BASE_URL}/api/backup/sync", headers=h1, json={
        'items': [
            {
                'id': str(uuid.uuid4()),
                'accountId': expected_g1_id,
                'accountEmail': g1_email,
                'fileName': 'vacation_2026.jpg',
                'fileType': 'photo',
                'mimeType': 'image/jpeg',
                'fileSizeBytes': 5242880,
                'cloudFileId': 'drive_file_id_001',
                'status': 'completed'
            },
            {
                'id': str(uuid.uuid4()),
                'accountId': expected_g2_id,
                'accountEmail': g2_email,
                'fileName': 'birthday_video.mp4',
                'fileType': 'video',
                'mimeType': 'video/mp4',
                'fileSizeBytes': 52428800,
                'cloudFileId': 'drive_file_id_002',
                'status': 'completed'
            }
        ]
    })
    assert sync_res.status_code == 200
    print("✓ Uploaded backup items into both Google accounts")

    # 5. SIMULATE PHONE 2 LOGIN:
    # User installs app on Phone 2 and logs in with SAME Master Account
    print("\n--- SIMULATING PHONE 2 LOGIN WITH MASTER ACCOUNT ---")
    login_phone2 = requests.post(f"{BASE_URL}/api/auth/login", json={
        'email': master_email,
        'password': pwd,
        'deviceName': 'Phone 2 (Samsung S24 Ultra)'
    })
    assert login_phone2.status_code == 200
    data2 = login_phone2.json()
    assert data2['user']['id'] == user_id, "User ID must be identical across devices!"
    token2 = data2['sessionToken']
    h2 = {'Authorization': f'Bearer {token2}', 'Content-Type': 'application/json'}

    # Phone 2 immediately receives connected accounts and backup history!
    assert len(data2['connectedAccounts']) == 2, f"Expected 2 accounts, got {len(data2['connectedAccounts'])}"
    assert len(data2['backupHistory']) == 2, f"Expected 2 backup files, got {len(data2['backupHistory'])}"
    print(f"✓ Phone 2 instant restore verified: {len(data2['connectedAccounts'])} Google accounts and {len(data2['backupHistory'])} files restored without re-upload!")

    # 6. Verify Phone 2 GET /api/user/sync and GET /api/backup/sync
    user_sync_get = requests.get(f"{BASE_URL}/api/user/sync", headers=h2).json()
    assert len(user_sync_get['connectedAccounts']) == 2
    backup_sync_get = requests.get(f"{BASE_URL}/api/backup/sync", headers=h2).json()
    assert len(backup_sync_get['backupHistory']) == 2
    print("✓ Phone 2 background polling/refresh APIs verified: /api/user/sync & /api/backup/sync return full state")

    # 7. Device isolation check
    devices_res = requests.get(f"{BASE_URL}/api/devices", headers=h2).json()
    device_names = [d['deviceName'] for d in devices_res['devices']]
    print(f"✓ Devices registered under Master Account: {device_names}")

    print("\n==================================================")
    print("ALL MULTI-ACCOUNT & CROSS-DEVICE TESTS PASSED 100%!")
    print("==================================================")

if __name__ == '__main__':
    test_multi_account_and_device_sync()
