#!/usr/bin/env python3
import pymysql
import uuid
from datetime import datetime

DB = dict(host='localhost', port=3306, database='xygbfpsg_loans',
          user='xygbfpsg_graz', password='j.ez-xy6##y.rllB',
          charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

BORROWER_ID = str(uuid.uuid4())
FIRST_NAME = 'John'
LAST_NAME = 'Doe'
ID_NUMBER = '12345678'
PHONE = '0712345678'
EMAIL = 'johndoe@example.com'

print("Creating test borrower...")

conn = pymysql.connect(**DB)
try:
    with conn.cursor() as cursor:
        # Find users table (borrowers are users with role='borrower')
        cursor.execute("SHOW TABLES LIKE 'users%'")
        tables = [list(t.values())[0] for t in cursor.fetchall()]
        
        if not tables:
            print("❌ No users table found!")
            exit(1)
        
        table_name = tables[0]
        print(f"Using table: {table_name}")
        
        # Get actual column names
        cursor.execute(f"DESCRIBE {table_name}")
        columns = {col['Field']: col['Type'] for col in cursor.fetchall()}
        print(f"Table has columns: {', '.join(list(columns.keys())[:10])}")
        
        # Map to actual column names
        phone_col = 'phone_number' if 'phone_number' in columns else 'phone'
        email_col = 'email' if 'email' in columns else None
        
        # Check if exists
        where_parts = []
        where_values = []
        
        if 'id_number' in columns:
            where_parts.append('id_number = %s')
            where_values.append(ID_NUMBER)
        
        if phone_col:
            where_parts.append(f'{phone_col} = %s')
            where_values.append(PHONE)
        
        where_clause = ' OR '.join(where_parts) if where_parts else '1=0'
        
        cursor.execute(f"SELECT id FROM {table_name} WHERE {where_clause}", where_values)
        existing = cursor.fetchone()
        
        if existing:
            print(f"⚠️  User exists: {existing['id']}")
            BORROWER_ID = existing['id']
        else:
            print("Creating borrower...")
            
            # Build insert with actual columns
            data = {}
            data['id'] = BORROWER_ID
            data['first_name'] = FIRST_NAME
            data['last_name'] = LAST_NAME
            data['role'] = 'borrower'
            data['is_staff'] = 0
            data['is_superuser'] = 0
            data['is_active'] = 1
            data['date_joined'] = datetime.now()
            
            if 'id_number' in columns:
                data['id_number'] = ID_NUMBER
            if phone_col:
                data[phone_col] = PHONE
            if email_col:
                data[email_col] = EMAIL
            if 'username' in columns:
                data['username'] = ID_NUMBER
            if 'password' in columns:
                data['password'] = ''
            
            fields = ', '.join(data.keys())
            placeholders = ', '.join(['%s'] * len(data))
            
            sql = f"INSERT INTO {table_name} ({fields}) VALUES ({placeholders})"
            cursor.execute(sql, list(data.values()))
            print("✅ Borrower created")
    
    conn.commit()
    
    # Verify
    with conn.cursor() as cursor:
        cursor.execute(f"SELECT id, first_name, last_name, role FROM {table_name} WHERE id = %s", 
                      (BORROWER_ID,))
        borrower = cursor.fetchone()
        
        if borrower:
            print("\n" + "="*60)
            print("✅ SUCCESS!")
            print("="*60)
            print(f"ID: {borrower['id']}")
            print(f"Name: {borrower['first_name']} {borrower['last_name']}")
            print(f"Role: {borrower['role']}")
            print("="*60)
        
finally:
    conn.close()
