import os
import requests
from flask import current_app

def cache_avatar(user_id, avatar_hash):
    """
    Downloads avatar from Discord and saves locally.
    Returns web-accessible path.
    """
    if not avatar_hash: 
        # For users without discriminator (new pomelo names), use (user_id >> 22) % 6
        default_index = (int(user_id) >> 22) % 6
        return f"https://cdn.discordapp.com/embed/avatars/{default_index}.png"
    
    # Ensure dir exists - getting root from app context
    static_folder = os.path.join(current_app.root_path, '..', 'static')
    avatar_dir = os.path.join(static_folder, 'avatars')
    if not os.path.exists(avatar_dir):
        os.makedirs(avatar_dir)

    filename = f"{user_id}_{avatar_hash}.png"
    local_path = os.path.join(avatar_dir, filename)
    web_path = f"/static/avatars/{filename}"
    
    # Return cache if exists
    if os.path.exists(local_path):
        return web_path
        
    url = f"https://cdn.discordapp.com/avatars/{user_id}/{avatar_hash}.png"
    try:
        res = requests.get(url, timeout=5)
        if res.status_code == 200:
            with open(local_path, 'wb') as f:
                f.write(res.content)
            return web_path
    except Exception as e:
        print(f"Avatar download failed: {e}")
        pass
    
    
    # Final fallback if download failed and we have a hash
    default_index = (int(user_id) >> 22) % 6
    return f"https://cdn.discordapp.com/embed/avatars/{default_index}.png"
