#!/usr/bin/env python3
import pymysql

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

print("=" * 60)
print("🔍 Checking Admin User and Permissions")
print("=" * 60)

conn = pymysql.connect(**DB)
try:
    with conn.cursor() as cursor:
        # Get admin user
        cursor.execute("SELECT id, username, role, is_staff, is_superuser FROM users WHERE username = 'admin'")
        admin = cursor.fetchone()
        
        if not admin:
            print("❌ Admin user not found!")
        else:
            print(f"\n👤 Admin User:")
            print(f"   Username: {admin['username']}")
            print(f"   Role: {admin['role']}")
            print(f"   is_staff: {admin['is_staff']}")
            print(f"   is_superuser: {admin['is_superuser']}")
            
            # Check if there are permission tables
            cursor.execute("SHOW TABLES LIKE '%permission%'")
            perm_tables = cursor.fetchall()
            
            print(f"\n📋 Permission Tables:")
            if perm_tables:
                for table in perm_tables:
                    print(f"   - {table}")
            else:
                print("   No permission tables found")
            
            # The issue: Since role is 'admin', has_permission should return True
            # But the code checks: if self.role == 'admin': return True
            print(f"\n✅ Permission Check Logic:")
            print(f"   Since role = '{admin['role']}'")
            print(f"   The code: if self.role == 'admin': return True")
            if admin['role'] == 'admin':
                print(f"   ✅ Should PASS - Admin has all permissions")
            else:
                print(f"   ❌ Will FAIL - Role doesn't match 'admin'")
        
        print("\n" + "=" * 60)
        print("🔍 ISSUE DIAGNOSIS:")
        print("=" * 60)
        
        if admin and admin['role'] == 'admin':
            print("✅ User role is 'admin' - permissions should work")
            print("\n💡 The issue might be:")
            print("   1. Cache - Django not reloaded after code changes")
            print("   2. Session - User session has old data")
            print("   3. Database connection - Using wrong DB")
            print("\n🔧 Solutions:")
            print("   1. Restart Django: touch tmp/restart.txt")
            print("   2. Clear browser cache and re-login")
            print("   3. Check Django is using correct database")
        
finally:
    conn.close()
