#!/usr/bin/env python3
"""Simule la requête API /weekly/:userId/avatars - version simplifiée"""

import mysql.connector
import json
from python.db_config import DB_CONFIG

conn = mysql.connector.connect(**DB_CONFIG)
cursor = conn.cursor(dictionary=True)

user_id = 1  # Bruno-admin

print("=" * 70)
print(f"VÉRIFICATION AVATARS POUR USER {user_id}")
print("=" * 70)

# 1. Vérifier user_avatars
print("\n1. user_avatars:")
cursor.execute("""
    SELECT ua.avatar_id, ua.source, ua.unlocked_at, a.file_path, a.code
    FROM user_avatars ua
    LEFT JOIN avatars a ON a.id = ua.avatar_id
    WHERE ua.user_id = %s
""", (user_id,))
ua_rows = cursor.fetchall()
print(f"   {len(ua_rows)} lignes")
for r in ua_rows:
    print(f"   - {r}")

# 2. Vérifier user_weekly_avatars
print("\n2. user_weekly_avatars:")
cursor.execute("""
    SELECT uwa.avatar_id, uwa.obtained_from, uwa.obtained_at, a.file_path, a.code
    FROM user_weekly_avatars uwa
    LEFT JOIN avatars a ON a.id = uwa.avatar_id
    WHERE uwa.user_id = %s
""", (user_id,))
uwa_rows = cursor.fetchall()
print(f"   {len(uwa_rows)} lignes")
for r in uwa_rows:
    print(f"   - {r}")

# 3. Construire la réponse comme l'API devrait le faire
print("\n3. RÉPONSE API SIMULÉE:")
avatars = []

# D'abord depuis user_avatars
for row in ua_rows:
    file_path = row['file_path']
    avatar_id = row['avatar_id']
    
    if file_path:
        avatar_path = f"/avatars/{file_path}"
    else:
        avatar_path = f"/avatars/380_animal_avatard/{avatar_id}.svg"
    
    avatars.append({
        'avatarId': avatar_id,
        'avatarCode': row['code'],
        'avatarPath': avatar_path,
        'obtainedFrom': row['source']
    })

# Puis depuis user_weekly_avatars (ceux pas dans user_avatars)
ua_ids = {r['avatar_id'] for r in ua_rows}
for row in uwa_rows:
    if row['avatar_id'] not in ua_ids:
        file_path = row['file_path']
        avatar_id = row['avatar_id']
        
        if file_path:
            avatar_path = f"/avatars/{file_path}"
        else:
            avatar_path = f"/avatars/380_animal_avatard/{avatar_id}.svg"
        
        avatars.append({
            'avatarId': avatar_id,
            'avatarCode': row['code'],
            'avatarPath': avatar_path,
            'obtainedFrom': row['obtained_from']
        })

print(f"   Total avatars: {len(avatars)}")
print(json.dumps({'avatars': avatars}, indent=2, default=str))

conn.close()
