#!/usr/bin/env python3
"""
Debug script to test email update step by step
"""

import urllib.request
import json

def test_email_update_debug():
    """Test email update with detailed debugging"""
    
    print("🔍 DEBUGGING EMAIL UPDATE ISSUE")
    print("=" * 50)
    
    # Step 1: Check current user details
    print("Step 1: Checking current user details...")
    user_id = "8dabf1ee-f9a1-465f-a200-8f080f914876"
    
    try:
        # GET request to check current user
        req = urllib.request.Request(f"https://kisiwaapi.mutabletech.co.ke/api/v1/users/{user_id}")
        with urllib.request.urlopen(req) as response:
            current_data = response.read().decode('utf-8')
            print(f"✅ Current user data retrieved (Status: {response.status})")
            
            # Parse and show current email
            try:
                data = json.loads(current_data)
                if data.get('success'):
                    user = data.get('data', {})
                    current_email = user.get('email', 'N/A')
                    print(f"📧 Current email in database: {current_email}")
                    
                    if current_email == "kosgeirene04@gmail.comI":
                        print("⚠️  Email still has the typo 'I' at the end")
                    else:
                        print(f"✅ Email appears to be correct: {current_email}")
                else:
                    print(f"❌ Failed to get user data: {data.get('data', 'Unknown error')}")
                    return
            except json.JSONDecodeError:
                print("❌ Response is not valid JSON")
                return
                
    except Exception as e:
        print(f"❌ Error getting current user: {e}")
        return
    
    print("\n" + "=" * 50)
    
    # Step 2: Try to update the email
    print("Step 2: Attempting to update email...")
    
    try:
        # PUT request to update email
        payload = {"email": "kosgeirene04@gmail.com"}
        data = json.dumps(payload).encode('utf-8')
        
        req = urllib.request.Request(
            f"https://kisiwaapi.mutabletech.co.ke/api/v1/users/{user_id}",
            data=data,
            method='PUT'
        )
        req.add_header('Content-Type', 'application/json')
        
        with urllib.request.urlopen(req) as response:
            update_response = response.read().decode('utf-8')
            print(f"✅ Update request completed (Status: {response.status})")
            print(f"📝 Update response: {update_response}")
            
            if response.status == 200:
                print("✅ Update API call successful!")
            else:
                print(f"❌ Update failed with status {response.status}")
                
    except Exception as e:
        print(f"❌ Error updating email: {e}")
        return
    
    print("\n" + "=" * 50)
    
    # Step 3: Verify the email was actually updated
    print("Step 3: Verifying email was updated...")
    
    try:
        # GET request to check if email was updated
        req = urllib.request.Request(f"https://kisiwaapi.mutabletech.co.ke/api/v1/users/{user_id}")
        with urllib.request.urlopen(req) as response:
            updated_data = response.read().decode('utf-8')
            print(f"✅ Verification request completed (Status: {response.status})")
            
            try:
                data = json.loads(updated_data)
                if data.get('success'):
                    user = data.get('data', {})
                    updated_email = user.get('email', 'N/A')
                    print(f"📧 Email after update: {updated_email}")
                    
                    if updated_email == "kosgeirene04@gmail.com":
                        print("🎉 SUCCESS: Email was updated correctly!")
                    elif updated_email == "kosgeirene04@gmail.comI":
                        print("❌ FAILED: Email still has the typo 'I' at the end")
                        print("🔍 This suggests the update is not being persisted to the database")
                    else:
                        print(f"❓ UNEXPECTED: Email is now '{updated_email}' (neither expected value)")
                else:
                    print(f"❌ Failed to verify update: {data.get('data', 'Unknown error')}")
            except json.JSONDecodeError:
                print("❌ Verification response is not valid JSON")
                
    except Exception as e:
        print(f"❌ Error verifying update: {e}")
        return
    
    print("\n" + "=" * 50)
    print("🔍 DEBUGGING COMPLETE")

if __name__ == "__main__":
    test_email_update_debug() 