import os
import time
from flask import Blueprint, render_template, redirect, session, request, url_for, render_template_string
from requests_oauthlib import OAuth2Session
from .utils.db import get_db
from .utils.avatars import cache_avatar

main_bp = Blueprint('main', __name__)

# Config - Should be in central config but keeping simple for now
CLIENT_ID = os.getenv("DISCORD_CLIENT_ID")
CLIENT_SECRET = os.getenv("DISCORD_CLIENT_SECRET")
REDIRECT_URI = "https://xorgus.ddns.net/callback"
API_BASE_URL = "https://discord.com/api"
AUTHORIZATION_BASE_URL = API_BASE_URL + "/oauth2/authorize"
TOKEN_URL = API_BASE_URL + "/oauth2/token"

@main_bp.route("/")
def index():
    return render_template("index.html")

@main_bp.route('/favicon.svg')
def favicon():
    # Flask serves static files from static_folder, but for root favicon usually need specific rule
    # or just let nginx handle it. relying on static folder setup.
    return main_bp.send_static_file('favicon.svg')

# --- AUTH ---
@main_bp.route("/login")
def login():
    discord = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URI, scope=["identify"])
    authorization_url, state = discord.authorization_url(AUTHORIZATION_BASE_URL)
    session["oauth_state"] = state
    return redirect(authorization_url)

@main_bp.route("/callback")
def callback():
    try:
        discord = OAuth2Session(CLIENT_ID, redirect_uri=REDIRECT_URI, state=session.get("oauth_state"))
        token = discord.fetch_token(TOKEN_URL, client_secret=CLIENT_SECRET, authorization_response=request.url)
        session["oauth_token"] = token
        
        user_data = discord.get(API_BASE_URL + "/users/@me").json()
        session["user_id"] = int(user_data["id"])
        session["username"] = user_data["username"]
        
        # USE NEW CACHE UTILITY
        session["avatar"] = cache_avatar(user_data["id"], user_data.get("avatar"))
    except Exception as e:
        return f"Auth Error: {e} <a href='/'>Back</a>"
    
    # Init User in DB
    try:
        conn = get_db()
        cur = conn.cursor()
        cur.execute("SELECT * FROM users WHERE user_id = ?", (session["user_id"],))
        if not cur.fetchone():
            cur.execute("INSERT INTO users (user_id, balance, username, avatar) VALUES (?, 0, ?, ?)", 
                       (session["user_id"], session["username"], session["avatar"]))
        else:
            cur.execute("UPDATE users SET username = ?, avatar = ? WHERE user_id = ?", 
                       (session["username"], session["avatar"], session["user_id"]))
        conn.commit()
    except Exception as e:
        print(f"DB Init Error: {e}")

    return redirect("/")

@main_bp.route("/logout")
def logout():
    session.clear()
    return redirect("/")

# --- VIEW CARD (PUBLIC) ---
@main_bp.route("/view/<seed>")
def view_card(seed):
    conn = get_db()
    cur = conn.cursor()
    
    cur.execute("SELECT * FROM cards WHERE seed = ?", (seed,))
    card_row = cur.fetchone()
    
    if not card_row:
        return "<h1>404 Not Found</h1>"
    
    card = dict(card_row)
    owner_id = card['owner_id']
    owner_name = f"ID: {owner_id}"
    owner_avatar = f"https://cdn.discordapp.com/embed/avatars/{(int(owner_id) >> 22) % 6}.png" 
    
    try:
        cur.execute("SELECT * FROM users WHERE user_id = ?", (owner_id,))
        user_row = cur.fetchone()
        if user_row:
            user_data = dict(user_row)
            if 'username' in user_data and user_data['username']: owner_name = user_data['username']
            # Use cached avatar if available in DB lookup, otherwise default
            # Note: The DB should have the cached path stored if they logged in recently
            # But let's check cache_avatar just in case user exists but avatar not downloaded? 
            # Actually easier to rely on DB 'avatar' column which we update on login
            if 'avatar' in user_data and user_data['avatar']:
                owner_avatar = user_data['avatar']
                # If it's a discord URL (old db), maybe nice to convert? For now trust DB.
    except Exception:
        pass
        
    art_seed = int(seed[:8], 16)
    # Расширенный список мемных предметов (COPY FROM LEGACY)
    emojis = [
        '🗿', '💀', '🤡', '👽', '👾', '🤖', '👻', '💩', '👺', '👹',
        '🧢', '🕶️', '🎩', '🦠', '🧬', '🧠', '👁️', '👄', '🦴',
        '💣', '🧨', '🔪', '🗡️', '⚔️', '🛡️', '🪓', '🔫', '🩸', '💊', '💉',
        '🚬', '⚰️', '🪦', '🧯', '🔨', '🔧', '🪚', '⚓', '⚖️',
        '🚀', '🛸', '🪐', '🌑', '☀️', '⚡', '🔥', '❄️', '🌪️', '🌊',
        '🔮', '🧿', '⚗️', '🕯️', '🔦', '🧭', '🗝️', '🚪',
        '💎', '👑', '💍', '🏆', '🥇', '💰', '💸', '💵', '💳', '🎰',
        '🎲', '🎱', '🎳', '🎮', '🕹️', '🎫', '🎁', '📦',
        '💻', '🖥️', '💾', '💿', '📼', '📷', '📹', '🎥', '📺', '📻',
        '📱', '📟', '📠', '🔋', '🔌', '📡', '🚗', '🚓', '🚜', '🏎️',
        '🍆', '🍑', '🍌', '🥑', '🌶️', '🌽', '🍄', '🌵', '🌲', '🍂',
        '🍔', '🍕', '🌭', '🌮', '🍣', '🍩', '🍪', '🍺', '🍷', '🥃',
        '🧂', '🍿', '🧀', '🍗', '🥩', '🍤', '🦞', '🦀',
        '🦍', '🦧', '🐕', '🐈', '🐅', '🦖', '🦕', '🦈', '🐊', '🐍',
        '🦅', '🦉', '🦇', '🦄', '🦆', '🦚', '🦜', '🦩', '🐀', '🐁',
        '🚽', '🧻', '🪠', '🧼', '🧽', '🧱', '🧸', '🪑', '🛌', '🛒',
        '🚨', '🛑', '🚩', '🏁', '🚫', '⚠️', '💢', '💤', '💥', '💦'
    ]
    main_emoji = emojis[art_seed % len(emojis)]
    rarity_class = card["rarity"].lower()
    
    shimmer_div = '<div class="shimmer-layer"></div>' if rarity_class in ['legendary', 'epic', 'rare'] else ''
    
    # Render template using formatted string (Moved to separate html file ideally, but keeping valid refactor scope)
    # Using the SAME HTML structure as in server.py to ensure consistency
    # For CLEANER CODE, we should ideally load this from a template file. 
    # But to minimize breakage, I will paste the corrected template string here.
    
    return render_template_string(f"""
    <!DOCTYPE html>
    <html lang="ru">
    <head>
        <link rel="icon" type="image/svg+xml" href="/favicon.svg">
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Xorgus Asset #{card['card_id']}</title>
        <link href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@300;500;700&family=Bad+Script&display=swap" rel="stylesheet">
        <style>
            :root {{ --bg: #050505; --glass-border: rgba(255, 255, 255, 0.1); }}
            body {{ background: #050505; color: #fff; font-family: 'Space Grotesk', sans-serif; display: flex; flex-direction: column; align-items: center; justify-content: center; min-height: 100vh; margin: 0; background: radial-gradient(circle at 50% 0%, #1a1a2e 0%, #000 80%); }}
            
            .card-wrapper {{ width: 300px; height: 480px; position: relative; }}
            .card {{ width: 100%; height: 100%; border-radius: 24px; position: relative; overflow: hidden; border: 1px solid rgba(255,255,255,0.1); box-shadow: 0 25px 50px -12px rgba(0,0,0,0.6); display: flex; flex-direction: column; }}
            .card {{ background: linear-gradient(135deg, #2b2b38 0%, #101015 100%); }}
            
            @keyframes shimmerMove {{ 0% {{ transform: translateX(-300%); }} 100% {{ transform: translateX(400%); }} }}
            .shimmer-layer {{
                position: absolute; top: 0; bottom: 0; width: 50%;
                background: linear-gradient(to right, transparent 0%, var(--shimmer-color, rgba(255,255,255,0.05)) 50%, transparent 100%);
                filter: blur(25px); opacity: 0.8; pointer-events: none; z-index: 10;
                transform: translateX(-300%);
                animation: shimmerMove 3.5s infinite linear;
                mix-blend-mode: overlay;
            }}

            .card-header {{ padding: 20px; display: flex; justify-content: space-between; z-index: 5; position: relative; }}
            .rarity-badge {{ font-size: 0.65rem; font-weight: 800; text-transform: uppercase; letter-spacing: 1px; padding: 5px 10px; border-radius: 12px; }}
            
            .card-art {{ height: 180px; display: flex; align-items: center; justify-content: center; font-size: 7rem; text-shadow: 0 10px 30px rgba(0,0,0,0.5); z-index: 5; position: relative; }}
            
            .card-body {{ padding: 0 20px; flex: 1; z-index: 5; position: relative; }}
            .stats-row {{ display: flex; gap: 10px; margin-bottom: 20px; }}
            .stat {{ background: rgba(255,255,255,0.05); padding: 8px; border-radius: 8px; flex: 1; text-align: center; border: 1px solid rgba(255,255,255,0.05); }}
            .stat span {{ display: block; }}
            
            .signature {{ font-family: 'Bad Script', cursive; font-size: 1.8rem; color: #e5e5e5; transform: rotate(-3deg); text-align: center; margin-top: 10px; text-shadow: 0 2px 4px rgba(0,0,0,0.8); }}
            
            .card-footer {{ padding: 15px 20px; background: rgb(16, 16, 22); border-top: 1px solid rgb(22 22 22); display: flex; align-items: center; gap: 10px; z-index: 5; position: relative; }}
            .owner-avatar {{ width: 32px; height: 32px; border-radius: 50%; }}
            
            .legendary {{ border-color: rgba(251, 191, 36, 0.5); box-shadow: 0 0 30px rgba(251, 191, 36, 0.15); }}
            .legendary .shimmer-layer {{ --shimmer-color: rgba(251, 191, 36, 0.4); animation-duration: 3s; }}
            .legendary .rarity-badge {{ background: #fbbf24; color: #000; }}
            
            .epic {{ border-color: rgba(192, 132, 252, 0.5); }}
            .epic .shimmer-layer {{ --shimmer-color: rgba(192, 132, 252, 0.35); animation-duration: 4s; }}
            .epic .rarity-badge {{ background: #c084fc; color: #fff; }}
            
            .rare {{ border-color: rgba(96, 165, 250, 0.5); }}
            .rare .shimmer-layer {{ --shimmer-color: rgba(96, 165, 250, 0.3); animation-duration: 5s; }}
            .rare .rarity-badge {{ background: #60a5fa; color: #000; }}
            
            .uncommon .rarity-badge {{ background: #4ade80; color: #000; }}
            .common .rarity-badge {{ background: #333; color: #888; }}
        </style>
    </head>
    <body>
        <div class="card-wrapper">
            <div class="card {rarity_class}">
                {shimmer_div}
                <div class="card-header">
                    <span class="rarity-badge">{card['rarity']}</span>
                    <span style="font-family:monospace; color:#555; font-size:0.8rem">#{card['card_id']}</span>
                </div>
                <div class="card-art">{main_emoji}</div>
                <div class="card-body">
                    <div class="stats-row">
                        <div class="stat"><span style="font-size:0.6rem; color:#888;">POWER</span><b>{card['power']}</b></div>
                        <div class="stat"><span style="font-size:0.6rem; color:#888;">LUCK</span><b>{card['luck']}%</b></div>
                    </div>
                    <div class="signature">{card['signature'] if card['signature'] else ''}</div>
                </div>
                <div class="card-footer">
                    <img src="{owner_avatar}" class="owner-avatar">
                    <div style="display:flex; flex-direction:column">
                        <span style="font-size:0.6rem; color:#666; line-height:1">OWNER</span>
                        <span style="font-size:0.8rem; font-weight:700">{owner_name}</span>
                    </div>
                </div>
            </div>
        </div>
        <p style="margin-top:20px; color:#4ade80; font-size:0.9rem">✓ Blockchain Verified Asset</p>
    </body>
    </html>
    """)
