import requests
import io
import json

BASE = 'http://127.0.0.1:5000'

def run_tests():
    print("=" * 60)
    print("CLOUDVAULT 2.0 – FULL ECOSYSTEM INTEGRATION TEST SUITE")
    print("=" * 60)

    # TEST 1: Health check & SPA serving
    print("\n[TEST 1] Checking Backend Health & React Web SPA Serving...")
    r_health = requests.get(f'{BASE}/health')
    assert r_health.status_code == 200, f"Health check failed: {r_health.text}"
    print("✓ Backend is healthy: 200 OK")

    r_spa = requests.get(f'{BASE}/')
    assert r_spa.status_code == 200 and '<div id="root">' in r_spa.text
    print("✓ React Web SPA served successfully at root: 200 OK")

    # TEST 2: Register user on Phone A
    test_email = "ecosystem_user@example.com"
    test_pwd = "EcosystemPass2026!"
    test_name = "Ecosystem Tester"

    print(f"\n[TEST 2] Registering user '{test_email}' from Phone A...")
    r_reg = requests.post(f'{BASE}/api/auth/register', json={
        'name': test_name,
        'email': test_email,
        'password': test_pwd,
        'deviceId': 'phone_a_hardware_uuid_777',
        'deviceName': 'Xiaomi Redmi Note 13 (Phone A)',
        'deviceType': 'android'
    })
    if r_reg.status_code == 409: # Already registered
        r_login_temp = requests.post(f'{BASE}/api/auth/login', json={'email': test_email, 'password': test_pwd})
        user_id_a = r_login_temp.json()['user']['id']
        token_a = r_login_temp.json()['token']
        print(f"✓ User already registered, retrieved User ID: {user_id_a}")
    else:
        assert r_reg.status_code == 201, f"Registration failed: {r_reg.text}"
        user_id_a = r_reg.json()['user']['id']
        token_a = r_reg.json()['token']
        print(f"✓ Registered on Phone A with User ID: {user_id_a}")

    headers_a = {'Authorization': f'Bearer {token_a}'}

    # TEST 3: Link Google Drive account
    print("\n[TEST 3] Linking Google Drive account to Phone A...")
    r_acc = requests.post(f'{BASE}/api/drive/accounts', headers=headers_a, json={
        'email': 'ecosystem_drive@gmail.com',
        'displayName': 'Ecosystem Cloud Drive',
        'providerAccountId': 'gdrive_user_9988'
    })
    assert r_acc.status_code in [200, 201], f"Connect account failed: {r_acc.text}"
    acc_id = r_acc.json()['account']['id']
    print(f"✓ Google Drive linked with ID: {acc_id}")

    # TEST 4: Phone A uploads a photo
    print("\n[TEST 4] Uploading photo from Phone A...")
    r_up_a = requests.post(f'{BASE}/api/drive/upload-complete', headers=headers_a, json={
        'filename': 'phone_a_family_photo.jpg',
        'fileSize': 3500000,
        'mimeType': 'image/jpeg',
        'accountId': acc_id,
        'sourceDevice': 'Xiaomi Redmi Note 13 (Phone A)'
    })
    assert r_up_a.status_code == 201, f"Phone A upload failed: {r_up_a.text}"
    print("✓ Phone A uploaded 'phone_a_family_photo.jpg' to My Drive/CloudVault/Photos")

    # TEST 5: Verify login on Phone B (Same credentials)
    print("\n[TEST 5] Logging in on Phone B with same credentials...")
    r_login_b = requests.post(f'{BASE}/api/auth/login', json={
        'email': test_email,
        'password': test_pwd,
        'deviceId': 'phone_b_hardware_uuid_888',
        'deviceName': 'Google Pixel 8 (Phone B)',
        'deviceType': 'android'
    })
    assert r_login_b.status_code == 200, f"Phone B login failed: {r_login_b.text}"
    b_data = r_login_b.json()
    user_id_b = b_data['user']['id']
    assert user_id_a == user_id_b, f"User IDs do not match! {user_id_a} != {user_id_b}"
    print(f"✓ Phone B logged in successfully with identical User ID: {user_id_b}")
    print(f"✓ Phone B instantly restored {len(b_data['connectedAccounts'])} connected accounts and {len(b_data['backupHistory'])} files!")

    token_b = b_data['token']
    headers_b = {'Authorization': f'Bearer {token_b}'}

    # TEST 6: Laptop Browser upload
    print("\n[TEST 6] Uploading document from Laptop Browser...")
    test_doc = io.BytesIO(b'Contract and financial documents CloudVault 2.0')
    r_web_up = requests.post(f'{BASE}/api/drive/upload-file', headers=headers_b, files={
        'file': ('tax_declaration_2026.pdf', test_doc, 'application/pdf')
    }, data={'sourceDevice': 'Chrome on Windows Laptop'})
    assert r_web_up.status_code == 201, f"Web upload failed: {r_web_up.text}"
    print("✓ Laptop browser uploaded 'tax_declaration_2026.pdf' to Google Drive")

    # TEST 7: Cross-Device Synchronization query
    print("\n[TEST 7] Querying files from Phone A to verify laptop upload is visible...")
    r_files_a = requests.get(f'{BASE}/api/drive/files', headers=headers_a)
    assert r_files_a.status_code == 200
    filenames = [f['filename'] for f in r_files_a.json()['files']]
    assert 'tax_declaration_2026.pdf' in filenames, "tax_declaration_2026.pdf not synced to Phone A!"
    print(f"✓ Phone A discovers {len(filenames)} files including the laptop-uploaded file!")

    # TEST 8: Storage Quota & Target check
    print("\n[TEST 8] Verifying Quota and Storage Targets...")
    r_quota = requests.get(f'{BASE}/api/storage/quota', headers=headers_a)
    assert r_quota.status_code == 200
    print(f"✓ Total Quota: {r_quota.json()['totalQuota']} bytes, Total Available: {r_quota.json()['totalAvailable']} bytes")

    # TEST 9: Devices Management check
    print("\n[TEST 9] Verifying registered devices...")
    r_dev = requests.get(f'{BASE}/api/devices', headers=headers_a)
    assert r_dev.status_code == 200
    dev_names = [d['deviceName'] for d in r_dev.json()['devices']]
    print(f"✓ Active devices registered: {dev_names}")

    # TEST 10: Settings update
    print("\n[TEST 10] Testing settings update...")
    r_set = requests.put(f'{BASE}/api/settings', headers=headers_a, json={
        'autoBackup': True,
        'wifiOnly': False,
        'storageThresholdPercent': 85
    })
    assert r_set.status_code == 200
    print(f"✓ Settings updated: threshold = {r_set.json()['settings']['storageThresholdPercent']}%")

    print("\n" + "=" * 60)
    print("🎉 ALL 10 INTEGRATION TESTS PASSED WITH ZERO ERRORS!")
    print("=" * 60)

if __name__ == '__main__':
    run_tests()
