#!/usr/bin/env python3
"""
Script to fix the email address by removing the extra "I" at the end
"""

import urllib.request
import urllib.parse
import json

def fix_email():
    """Fix the email address by removing the extra 'I'"""
    
    # API endpoint to update the user
    user_id = "8dabf1ee-f9a1-465f-a200-8f080f914876"  # From the check_users output
    url = f"https://kisiwaapi.mutabletech.co.ke/api/v1/users/{user_id}"
    
    # Payload to update the email
    payload = {
        "email": "kosgeirene04@gmail.com"  # Fixed email without the "I"
    }
    
    # Convert to JSON
    data = json.dumps(payload).encode('utf-8')
    
    # Create PUT request
    req = urllib.request.Request(url, data=data, method='PUT')
    req.add_header('Content-Type', 'application/json')
    
    try:
        # Make the request
        with urllib.request.urlopen(req) as response:
            response_data = response.read().decode('utf-8')
            print(f"Status Code: {response.status}")
            print(f"Response: {response_data}")
            
            if response.status == 200:
                print("✅ Email updated successfully!")
                print(f"Changed from: kosgeirene04@gmail.comI")
                print(f"Changed to: kosgeirene04@gmail.com")
                
                # Now test the password update with the corrected email
                print("\n" + "="*50)
                print("Now testing password update with corrected email...")
                test_password_update()
            else:
                print("❌ Failed to update email")
                
    except urllib.error.HTTPError as e:
        print(f"❌ HTTP Error: {e.code}")
        print(f"Response: {e.read().decode('utf-8')}")
    except urllib.error.URLError as e:
        print(f"❌ URL Error: {e.reason}")
    except Exception as e:
        print(f"❌ Error: {e}")

def test_password_update():
    """Test the password update with the corrected email"""
    
    # API endpoint
    url = "https://kisiwaapi.mutabletech.co.ke/api/v1/users/password/update"
    
    # Payload with corrected email
    payload = {
        "email": "kosgeirene04@gmail.com",  # Now using the corrected email
        "new_password": "Irene@2025"
    }
    
    # Convert to JSON
    data = json.dumps(payload).encode('utf-8')
    
    # Create request
    req = urllib.request.Request(url, data=data)
    req.add_header('Content-Type', 'application/json')
    
    try:
        # Make the request
        with urllib.request.urlopen(req) as response:
            response_data = response.read().decode('utf-8')
            print(f"Password Update Status Code: {response.status}")
            print(f"Password Update Response: {response_data}")
            
            if response.status == 200:
                print("✅ Password updated successfully!")
                try:
                    data = json.loads(response_data)
                    if data.get('success'):
                        print(f"User ID: {data['data']['user_id']}")
                        print(f"Email: {data['data']['email']}")
                        print(f"Updated at: {data['data']['updated_at']}")
                except json.JSONDecodeError:
                    print("Response is not valid JSON")
            else:
                print("❌ Failed to update password")
                
    except urllib.error.HTTPError as e:
        print(f"❌ HTTP Error: {e.code}")
        print(f"Response: {e.read().decode('utf-8')}")
    except urllib.error.URLError as e:
        print(f"❌ URL Error: {e.reason}")
    except Exception as e:
        print(f"❌ Error: {e}")

if __name__ == "__main__":
    print("Fixing email address and updating password...")
    print("=" * 60)
    print("Step 1: Fix email from 'kosgeirene04@gmail.comI' to 'kosgeirene04@gmail.com'")
    print("Step 2: Update password to 'Irene@2025'")
    print("=" * 60)
    
    fix_email() 