import requests
import uuid

BASE_URL = 'http://127.0.0.1:5000'

def test_multi_user_strict_isolation():
    print("==================================================")
    print("TESTING STRICT MULTI-USER / TEAMMATE DATA ISOLATION")
    print("==================================================")

    # -------------------------------------------------------------------------
    # USER 1: AMAN (Main User)
    # -------------------------------------------------------------------------
    aman_email = f"aman_{uuid.uuid4().hex[:6]}@example.com"
    res1 = requests.post(f"{BASE_URL}/api/auth/register", json={
        'email': aman_email,
        'password': 'amanpassword123',
        'displayName': 'Aman Sen',
        'deviceName': 'Aman Phone'
    })
    assert res1.status_code == 201
    aman_id = res1.json()['user']['id']
    aman_headers = {'Authorization': f"Bearer {res1.json()['sessionToken']}", 'Content-Type': 'application/json'}

    # Aman links 2 Google accounts (15GB + 15GB = 30GB pool)
    requests.post(f"{BASE_URL}/api/drive/accounts", headers=aman_headers, json={'email': 'aman_photos@gmail.com', 'displayName': 'Aman Photos'})
    requests.post(f"{BASE_URL}/api/drive/accounts", headers=aman_headers, json={'email': 'aman_work@gmail.com', 'displayName': 'Aman Work'})

    # Aman uploads 2 files
    requests.post(f"{BASE_URL}/api/backup/sync", headers=aman_headers, json={
        'items': [
            {'fileName': 'aman_vacation.jpg', 'fileType': 'photo', 'fileSizeBytes': 4000000, 'cloudFileId': 'aman_c1'},
            {'fileName': 'aman_report.pdf', 'fileType': 'document', 'fileSizeBytes': 1500000, 'cloudFileId': 'aman_c2'}
        ]
    })
    print(f"✓ User 1 (Aman: {aman_email}) set up with 2 Drives and 2 Files")

    # -------------------------------------------------------------------------
    # USER 2: RAHUL (Friend)
    # -------------------------------------------------------------------------
    rahul_email = f"rahul_{uuid.uuid4().hex[:6]}@example.com"
    res2 = requests.post(f"{BASE_URL}/api/auth/register", json={
        'email': rahul_email,
        'password': 'rahulpassword123',
        'displayName': 'Rahul Verma',
        'deviceName': 'Rahul Phone'
    })
    assert res2.status_code == 201
    rahul_id = res2.json()['user']['id']
    rahul_headers = {'Authorization': f"Bearer {res2.json()['sessionToken']}", 'Content-Type': 'application/json'}

    # Verify Rahul initially starts completely empty
    rahul_init_accs = requests.get(f"{BASE_URL}/api/drive/accounts", headers=rahul_headers).json()
    assert len(rahul_init_accs['accounts']) == 0, "New friend account must not see any existing accounts!"
    rahul_init_files = requests.get(f"{BASE_URL}/api/drive/files", headers=rahul_headers).json()
    assert len(rahul_init_files['files']) == 0, "New friend account must not see any existing files!"

    # Rahul links his OWN Google account (15GB)
    requests.post(f"{BASE_URL}/api/drive/accounts", headers=rahul_headers, json={'email': 'rahul_personal_drive@gmail.com', 'displayName': 'Rahul Drive'})

    # Rahul uploads his OWN files
    requests.post(f"{BASE_URL}/api/backup/sync", headers=rahul_headers, json={
        'items': [
            {'fileName': 'rahul_college_notes.pdf', 'fileType': 'document', 'fileSizeBytes': 800000, 'cloudFileId': 'rahul_c1'},
            {'fileName': 'rahul_family.jpg', 'fileType': 'photo', 'fileSizeBytes': 3200000, 'cloudFileId': 'rahul_c2'},
            {'fileName': 'rahul_tour.mp4', 'fileType': 'video', 'fileSizeBytes': 25000000, 'cloudFileId': 'rahul_c3'}
        ]
    })
    print(f"✓ User 2 (Rahul / Friend: {rahul_email}) set up with 1 Drive and 3 Files")

    # -------------------------------------------------------------------------
    # USER 3: SHIV (Teammate)
    # -------------------------------------------------------------------------
    shiv_email = f"shiv_{uuid.uuid4().hex[:6]}@example.com"
    res3 = requests.post(f"{BASE_URL}/api/auth/register", json={
        'email': shiv_email,
        'password': 'shivpassword123',
        'displayName': 'Shiv Rana',
        'deviceName': 'Shiv Device'
    })
    assert res3.status_code == 201
    shiv_id = res3.json()['user']['id']
    shiv_headers = {'Authorization': f"Bearer {res3.json()['sessionToken']}", 'Content-Type': 'application/json'}

    # Shiv links his OWN Google account
    requests.post(f"{BASE_URL}/api/drive/accounts", headers=shiv_headers, json={'email': 'shiv_work_drive@gmail.com', 'displayName': 'Shiv Work Drive'})

    # Shiv uploads his OWN file
    requests.post(f"{BASE_URL}/api/backup/sync", headers=shiv_headers, json={
        'items': [
            {'fileName': 'shiv_architecture_diagram.png', 'fileType': 'photo', 'fileSizeBytes': 1200000, 'cloudFileId': 'shiv_c1'}
        ]
    })
    print(f"✓ User 3 (Shiv / Teammate: {shiv_email}) set up with 1 Drive and 1 File")

    # -------------------------------------------------------------------------
    # STRICT CROSS-VERIFICATION & ZERO-LEAK ASSERTIONS
    # -------------------------------------------------------------------------
    print("\n--- RUNNING STRICT DATA ISOLATION ASSERTIONS ---")

    # 1. Aman's Data Verification
    aman_accs = requests.get(f"{BASE_URL}/api/drive/accounts", headers=aman_headers).json()['accounts']
    aman_files = requests.get(f"{BASE_URL}/api/drive/files", headers=aman_headers).json()['files']
    aman_quota = requests.get(f"{BASE_URL}/api/storage/quota", headers=aman_headers).json()

    assert len(aman_accs) == 2, f"Aman must see exactly 2 accounts, got {len(aman_accs)}"
    assert {a['providerEmail'] for a in aman_accs} == {'aman_photos@gmail.com', 'aman_work@gmail.com'}
    assert len(aman_files) == 2, f"Aman must see exactly 2 files, got {len(aman_files)}"
    assert aman_quota['totalQuota'] == 16106127360 * 2
    print("✓ Aman's account pool is strictly isolated: sees ONLY his 2 Drives and 2 Files")

    # 2. Rahul's Data Verification
    rahul_accs = requests.get(f"{BASE_URL}/api/drive/accounts", headers=rahul_headers).json()['accounts']
    rahul_files = requests.get(f"{BASE_URL}/api/drive/files", headers=rahul_headers).json()['files']
    rahul_quota = requests.get(f"{BASE_URL}/api/storage/quota", headers=rahul_headers).json()

    assert len(rahul_accs) == 1, f"Rahul must see exactly 1 account, got {len(rahul_accs)}"
    assert rahul_accs[0]['providerEmail'] == 'rahul_personal_drive@gmail.com'
    assert len(rahul_files) == 3, f"Rahul must see exactly 3 files, got {len(rahul_files)}"
    assert {f['filename'] for f in rahul_files} == {'rahul_college_notes.pdf', 'rahul_family.jpg', 'rahul_tour.mp4'}
    assert rahul_quota['totalQuota'] == 16106127360
    print("✓ Rahul (Friend) is strictly isolated: sees ONLY his 1 Drive and 3 Files. 0 leaked from Aman or Shiv!")

    # 3. Shiv's Data Verification
    shiv_accs = requests.get(f"{BASE_URL}/api/drive/accounts", headers=shiv_headers).json()['accounts']
    shiv_files = requests.get(f"{BASE_URL}/api/drive/files", headers=shiv_headers).json()['files']
    shiv_quota = requests.get(f"{BASE_URL}/api/storage/quota", headers=shiv_headers).json()

    assert len(shiv_accs) == 1
    assert shiv_accs[0]['providerEmail'] == 'shiv_work_drive@gmail.com'
    assert len(shiv_files) == 1
    assert shiv_files[0]['filename'] == 'shiv_architecture_diagram.png'
    assert shiv_quota['totalQuota'] == 16106127360
    print("✓ Shiv (Teammate) is strictly isolated: sees ONLY his 1 Drive and 1 File. 0 leaked from Aman or Rahul!")

    # 4. Rahul Cross-Device Login Simulation (Rahul installs APK on new phone)
    print("\n--- SIMULATING RAHUL LOGGING IN ON A SECOND PHONE ---")
    rahul_device2 = requests.post(f"{BASE_URL}/api/auth/login", json={
        'email': rahul_email,
        'password': 'rahulpassword123',
        'deviceName': 'Rahul Tablet'
    }).json()

    assert rahul_device2['user']['id'] == rahul_id
    assert len(rahul_device2['connectedAccounts']) == 1
    assert rahul_device2['connectedAccounts'][0]['email'] == 'rahul_personal_drive@gmail.com'
    assert len(rahul_device2['backupHistory']) == 3
    print("✓ Cross-Device Restore: Rahul on second device restores ONLY Rahul's Drive and 3 files perfectly!")

    print("\n==================================================")
    print("MULTI-USER & TEAMMATE STRICT ISOLATION PASSED 100%!")
    print("==================================================")

if __name__ == '__main__':
    test_multi_user_strict_isolation()
