import requests
import json
import uuid

BASE_URL = 'http://127.0.0.1:5000'

def test_audit():
    print("==================================================")
    print("STARTING CLOUDVAULT 2.0 WEBSITE & MULTI-DEVICE AUDIT")
    print("==================================================")

    # SCENARIO 1: Existing User Login (amansen2710@gmail.com)
    print("\n--- SCENARIO 1: Existing User Login (amansen2710@gmail.com) ---")
    res = requests.post(f"{BASE_URL}/api/auth/login", json={
        'email': 'amansen2710@gmail.com',
        'password': 'password123'
    })
    assert res.status_code == 200, f"Login failed: {res.text}"
    aman_data = res.json()
    token = aman_data['token']
    headers = {'Authorization': f"Bearer {token}"}
    print("✓ Login successful, JWT token received")

    # SCENARIO 2: Dashboard Storage Quota & Backed Up Files Check
    print("\n--- SCENARIO 2: Dashboard Quota & Stats Consistency ---")
    quota_res = requests.get(f"{BASE_URL}/api/storage/quota", headers=headers)
    assert quota_res.status_code == 200
    q_data = quota_res.json()
    print("Quota Data:", q_data)
    assert len(q_data['accountBreakdown']) == 1, f"Expected 1 account, got {len(q_data['accountBreakdown'])}"
    assert q_data['totalFiles'] == 101, f"Expected 101 files, got {q_data['totalFiles']}"
    assert q_data['totalQuota'] == 16106127360, f"Expected 16106127360 quota, got {q_data['totalQuota']}"
    assert q_data['totalCloudVaultUsage'] > 0, "CloudVault usage should be > 0"
    print("✓ Dashboard returns accurate real counts: 1 account, 101 files, real usage bytes")

    # SCENARIO 3: Connected Accounts Page Consistency
    print("\n--- SCENARIO 3: Connected Accounts API Check ---")
    acc_res = requests.get(f"{BASE_URL}/api/drive/accounts", headers=headers)
    assert acc_res.status_code == 200
    accounts = acc_res.json()['accounts']
    assert len(accounts) == 1, f"Expected 1 account, got {len(accounts)}"
    primary_acc = accounts[0]
    print(f"Primary Account: {primary_acc['providerEmail']}, Status: {primary_acc['connectionStatus']}")
    assert primary_acc['providerEmail'] == 'dorimonojha22@gmail.com'
    assert primary_acc['isActiveBackup'] == True
    print("✓ Connected Accounts matches Dashboard exactly: 1 account (dorimonojha22@gmail.com)")

    # SCENARIO 4: Account Sync & Quota Refresh Actions
    print("\n--- SCENARIO 4: Account Sync & Quota Refresh Actions ---")
    sync_res = requests.post(f"{BASE_URL}/api/drive/accounts/{primary_acc['id']}/sync", headers=headers)
    assert sync_res.status_code == 200
    sync_data = sync_res.json()
    print("Sync Result:", sync_data['message'], "Files Count:", sync_data['filesCount'])
    assert sync_data['filesCount'] == 101

    refresh_res = requests.post(f"{BASE_URL}/api/drive/accounts/{primary_acc['id']}/refresh-quota", headers=headers)
    assert refresh_res.status_code == 200
    print("✓ Sync and Quota Refresh executed successfully")

    # SCENARIO 5: Edit Storage Target
    print("\n--- SCENARIO 5: Edit Storage Target ---")
    target_res = requests.put(f"{BASE_URL}/api/drive/accounts/{primary_acc['id']}/target", headers=headers, json={
        'targetStorageGB': 12
    })
    assert target_res.status_code == 200
    target_data = target_res.json()
    print("Updated Target:", target_data['storageTarget'])
    assert target_data['storageTarget']['targetStorage'] == 12 * 1024 * 1024 * 1024
    print("✓ Storage Target successfully updated to 12 GB")

    # SCENARIO 6: User Profile & Security API
    print("\n--- SCENARIO 6: User Profile & Security API ---")
    profile_res = requests.get(f"{BASE_URL}/api/auth/me", headers=headers)
    assert profile_res.status_code == 200
    prof_data = profile_res.json()
    assert prof_data['email'] == 'amansen2710@gmail.com'
    assert prof_data['accountStatus'] == 'active'
    assert 'createdAt' in prof_data
    assert 'lastLogin' in prof_data
    assert 'securityInfo' in prof_data
    print(f"User: {prof_data['email']}, ID: {prof_data['userId']}, Created: {prof_data['createdAt']}")
    print("✓ Profile contains server-verified identity, security info, and timestamps")

    # SCENARIO 7: Change Password API
    print("\n--- SCENARIO 7: Change Password API ---")
    pw_res = requests.post(f"{BASE_URL}/api/auth/change-password", headers=headers, json={
        'currentPassword': 'password123',
        'newPassword': 'password123'
    })
    assert pw_res.status_code == 200
    print("✓ Password update validated and preserved")

    # SCENARIO 8: Files Catalog, Filtering & Search
    print("\n--- SCENARIO 8: Files Catalog, Filtering & Search ---")
    files_res = requests.get(f"{BASE_URL}/api/drive/files?limit=10", headers=headers)
    assert files_res.status_code == 200
    f_data = files_res.json()
    assert f_data['total'] == 101
    assert len(f_data['files']) == 10
    first_file = f_data['files'][0]
    print(f"First File: {first_file['fileName']}, Size: {first_file['fileSize']} bytes")
    assert first_file['googleDriveFileId'] is not None

    # Search for specific file
    search_res = requests.get(f"{BASE_URL}/api/drive/files?search=IMG_0005", headers=headers)
    assert search_res.status_code == 200
    s_files = search_res.json()['files']
    assert len(s_files) >= 1
    assert 'IMG_0005' in s_files[0]['fileName']
    print(f"✓ Search successfully found {len(s_files)} matches for 'IMG_0005'")

    # SCENARIO 9: Multi-Tenant Isolation (Register brand new user)
    print("\n--- SCENARIO 9: Multi-Tenant Isolation with New User ---")
    new_email = f"audit_user_{uuid.uuid4().hex[:6]}@example.com"
    reg_res = requests.post(f"{BASE_URL}/api/auth/register", json={
        'email': new_email,
        'password': 'auditPassword!2026',
        'displayName': 'Audit Tester'
    })
    assert reg_res.status_code == 201
    new_user_token = reg_res.json()['sessionToken']
    new_headers = {'Authorization': f"Bearer {new_user_token}"}

    # Verify new user has strictly ZERO accounts and ZERO files (no fake mock fallbacks!)
    new_quota = requests.get(f"{BASE_URL}/api/storage/quota", headers=new_headers).json()
    assert len(new_quota['accountBreakdown']) == 0, "New user must have 0 accounts"
    assert new_quota['totalFiles'] == 0, "New user must have 0 files"
    assert new_quota['totalQuota'] == 0, "New user quota must be 0"
    assert new_quota['totalUsed'] == 0, "New user total used must be 0"

    new_accs = requests.get(f"{BASE_URL}/api/drive/accounts", headers=new_headers).json()
    assert len(new_accs['accounts']) == 0, "New user connected accounts must be empty"

    new_files = requests.get(f"{BASE_URL}/api/drive/files", headers=new_headers).json()
    assert new_files['total'] == 0, "New user files must be 0"
    print("✓ Strict multi-tenant isolation verified: new user sees 0 accounts and 0 files")

    # SCENARIO 10: Connect Account for New User & Sync
    print("\n--- SCENARIO 10: Connect Account for New User & Sync ---")
    conn_res = requests.post(f"{BASE_URL}/api/drive/accounts", headers=new_headers, json={
        'email': 'new_drive_acc@gmail.com',
        'displayName': 'New User Drive'
    })
    assert conn_res.status_code == 201
    conn_acc = conn_res.json()['account']
    print("New Account Connected:", conn_acc['providerEmail'])

    # Verify Dashboard updates immediately
    upd_quota = requests.get(f"{BASE_URL}/api/storage/quota", headers=new_headers).json()
    assert len(upd_quota['accountBreakdown']) == 1, "Dashboard should now show 1 account"
    assert upd_quota['totalQuota'] == 16106127360, "Quota updated to 15 GB"
    print("✓ Dashboard and Connected Accounts synchronized immediately for new user")

    # SCENARIO 11: Disconnect Account
    print("\n--- SCENARIO 11: Disconnect Account ---")
    del_res = requests.delete(f"{BASE_URL}/api/drive/accounts/{conn_acc['id']}", headers=new_headers)
    assert del_res.status_code == 200

    # Verify Dashboard immediately reflects 0 accounts again
    del_quota = requests.get(f"{BASE_URL}/api/storage/quota", headers=new_headers).json()
    assert len(del_quota['accountBreakdown']) == 0
    assert del_quota['totalQuota'] == 0
    print("✓ Disconnect immediately updates all pages and removes account")

    # SCENARIO 12: Public Edge Tunnel Access Verification
    print("\n--- SCENARIO 12: Public Edge Tunnel Access Verification ---")
    tunnel_res = requests.get('https://creek-application-forestry-track.trycloudflare.com/health', timeout=10)
    assert tunnel_res.status_code == 200
    print("Tunnel Health:", tunnel_res.json())
    print("✓ Public Cloudflare Edge tunnel reachable globally on 4G/5G mobile networks")

    # SCENARIO 13: Web SPA Asset Serving
    print("\n--- SCENARIO 13: Web SPA Asset Serving ---")
    spa_res = requests.get(f"{BASE_URL}/")
    assert spa_res.status_code == 200
    assert '<title>CloudVault 2.0</title>' in spa_res.text or '<div id="root">' in spa_res.text
    print("✓ Flask successfully serves compiled React SPA from dist/index.html")

    print("\n==================================================")
    print("ALL 13 AUDIT SCENARIOS PASSED WITH 100% SUCCESS!")
    print("==================================================")

if __name__ == '__main__':
    test_audit()
