"""
INDUNGI VultStrike Arena Extension (Matchmaking, 1v1/2v2/5v5 Queues, Match Lobby & Case Opening)
"""
from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel, Field
from typing import Optional, Dict, Any, List
import uuid
import random
import time
from datetime import datetime, timezone, timedelta

def now_iso():
    return datetime.now(timezone.utc).isoformat()

# ================= CASES & SKINS CONFIGURATION =================
CASES_CATALOG = [
    {
        "id": "case_revolution",
        "name": "Revolution Case",
        "price": 250,
        "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFU1nfbOIj8W7oWzkYLdlPOsMOmIk2lu5cB1g_zMyoD0m1nkrhdpMW3wLYeLMlhprSEU4dQ/360fx360f",
        "description": "Include skinuri celebre: AK-47 Head Shot, M4A4 Temukau și mănuși speciale.",
        "skins": [
            {"id": "rev_1", "weapon": "MP9", "name": "Featherweight", "rarity": "mil-spec", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpou6r8FABz7P7NYgJB49G5mpS0m_7zO6-fzj9V65x037nF8Nms2wXsr0RqYmH6I9eRdgc3NAyFrwW8kuvxxcjr50D57wE/360fx360f", "price": 40},
            {"id": "rev_2", "weapon": "MAG-7", "name": "Insomnia", "rarity": "mil-spec", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpou7umeldf0Ob3fDxBvYyJmo-Mm_j4OrzZglRd6dd2j6eU89un3Vbs_0dqMG-gcoedJgVqZQ3V_QW_lOm9h5O8uJzAzXc2uD5iuyh8g2p0sQ/360fx360f", "price": 45},
            {"id": "rev_3", "weapon": "MAC-10", "name": "Sakkaku", "rarity": "restricted", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpou7umeldf0v33YzxL6eO7kZOdqPv9NLPF2DgHv8R33OuV8NzxjFW3-ENpMWzwctSTewZqYVzTrFW_yL-9jcPotZ3MziE27HYk5CvcnkGwh01SLrs4-4b_sB8/360fx360f", "price": 120},
            {"id": "rev_4", "weapon": "P90", "name": "Neoqueen", "rarity": "restricted", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpopuP1FAR17P7NYgJB49G5mpS0m_7zO6-fkDgB65wo2-yW8dmm3QOx-0Vqam-mLIaQdQc6ZFyF_lXtk-_u1JLqu5vKmCBm7yUi-z-DyPj5r10k/360fx360f", "price": 140},
            {"id": "rev_5", "weapon": "AWP", "name": "Duality", "rarity": "classified", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot621FAR17P7NYgJB49G5mpS0m_7zO6-fkDgH6sR33bDH9N2i2wW2-BVuNWGldtWVJAY8NVrV_1jowevogcO56pnAmHFm6yQl537cmUG1hh1SLrs4T_dE7gA/360fx360f", "price": 380},
            {"id": "rev_6", "weapon": "UMP-45", "name": "Wild Child", "rarity": "classified", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpoo7e1f1Jf0Ob3fDxBvYyJmo-Mm_j4OrzZglRd6dd2j6fD89_32QfnrUdpMWrwctORdwBoZ1rT_wS5w-y-jMe16cvMnyM17HYg7X7cnEDkiR1SLrs4-4b5N0o/360fx360f", "price": 420},
            {"id": "rev_7", "weapon": "M4A4", "name": "Temukau", "rarity": "covert", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpou-6kejhz2v_Nfz5H_uO1gb-Gw_alIITBhGJf_NZlmOzA-LP5gVO8v11rMTvydo-UdwI7N1nV-wS6weu505TouZ7AziE3vHErsH-InhblgBhSLrs4Y4Wk5sM/360fx360f", "price": 1250},
            {"id": "rev_8", "weapon": "AK-47", "name": "Head Shot", "rarity": "covert", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot7HxfDhjxszJemkV092lnYmGmOHLPr7Dk25f18l4jeHVu9miiQPt-UNkNWn3cdPDdgA8Y1DXq1K7xee5jcC97szOmyBi6yAn7SrdnQv330_5pB8mNA/360fx360f", "price": 1600},
            {"id": "rev_gold", "weapon": "★ Specialist Gloves", "name": "Marble Fade", "rarity": "extraordinary", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpovbSsLQJfxPrZTj5X09ujgZKKkuXLP7LWnn8fvcEi2L6U89ii2VDg_0dtNTz0dYDDegM4NAnZqQLsxr_mhsS_up_BzSBi7z5iuyjfnkMmhQ/360fx360f", "price": 4500}
        ]
    },
    {
        "id": "case_kilowatt",
        "name": "Kilowatt Case (CS2)",
        "price": 350,
        "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFU4naLOJjgUu9m3l4bew_StZ-jVzj5VvcZ03rqR896k2wXl-kBtZW-mLY-VcwRsYF3R-FS3wbzsh5S5vpqYzXA263Z27XqOmkG1hhxIbOBs0qCeS1-aUfcfQLXZbg7X4kE/360fx360f",
        "description": "Prima cutie oficială lansată în Counter-Strike 2 cu noul cuțit Kukri Knife!",
        "skins": [
            {"id": "kilo_1", "weapon": "Dual Berettas", "name": "Hideout", "rarity": "mil-spec", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpos7asPwJf0Ob3dChB0924nYeOm_LLPr7Vn35cpsB0j-qWpIn33FG2_0FvYGGnIdedJwVqY1uC_Qe_lenmhMS8v87JyXZr6HQn53ffnhG11RhFcKUx0upn11bK/360fx360f", "price": 50},
            {"id": "kilo_2", "weapon": "SSG 08", "name": "Dezastre", "rarity": "restricted", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpopamie19f0Ob3Yi5FvISJmIGZk8j8NrrHjyVT650p3b7C8Nmj0QznrkVoa2D1do6RdAFsZlnX-lO9yee505e8up7Kz3Fi6yMm5nndzQv3308D6Z4uRw/360fx360f", "price": 160},
            {"id": "kilo_3", "weapon": "M4A1-S", "name": "Black Lotus", "rarity": "classified", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpou-6kejhz2v_Nfz5H_uOxh7-Gw_alIITBhGJf18l4jeHVu4rz31Xk-hA_a2ymLNSdcg84YFnXqFa-l-u50ZPt75SfnHBrvHYn-z-DyG2qO5Jt/360fx360f", "price": 480},
            {"id": "kilo_4", "weapon": "AK-47", "name": "Inheritance", "rarity": "covert", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot7HxfDhjxszJemkV09-5lpKKqPrxN7LEmyVU7Pp8j-3I4IG7jgLl-BZuZWmgcNTDJ1RsYw6D_VW5k-6-jcDv6cvMyXdluyhwsnmPnRfmhB9SLrs47VqY7kM/360fx360f", "price": 1800},
            {"id": "kilo_5", "weapon": "AWP", "name": "Chrome Cannon", "rarity": "covert", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot621FAR17P7NYgJB49G5mpS0luX8P6jVqWZU7Mxkh6eZ8dqg3AGx-kdoMTymIoWccQI_aQzU_Vi9k-jphJa-uMnLzSNnuyZw-z-DyO4262Z4/360fx360f", "price": 1950},
            {"id": "kilo_gold", "weapon": "★ Kukri Knife", "name": "Fade", "rarity": "extraordinary", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpovbSsLQJf1fLEcjVL49KJlY20k_jkI7fUhGJP68BAC-bb84mj3Fay-0toY27wcI6RdQE_Z1HW8wDvyebngcTt6cjImCdm7CU8pSGKqWp6b9w/360fx360f", "price": 5500}
        ]
    },
    {
        "id": "case_indungi_legend",
        "name": "★ INDUNGI Legend Gold Case",
        "price": 600,
        "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFUynfWaIT8bvdizkIPdwaWkZr7UwD5Uv8ck3LzH846m2FfiqkNuZ2rzcI-TdwA4MFjX_wLtlOi5h5TvvM_KnHA17yV37GGdwUL8iF6qHQ/360fx360f",
        "description": "Ediție Specială Exclusivă INDUNGI cu șanse ridicate la cuțite Karambit & Butterfly!",
        "skins": [
            {"id": "ind_1", "weapon": "Glock-18", "name": "Vogue", "rarity": "restricted", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgposbaqKAxf0Ob3djFN79eJmo-Mm_j4OrzZglRd6dd2j6eT8dys3AXk-ktoZTigJ9SWcwZsM1nXqFftk-rsjcS7u5qbyXFi6XUr7HeMnEDjhB5SLrs4vU2T1Q0/360fx360f", "price": 180},
            {"id": "ind_2", "weapon": "Desert Eagle", "name": "Printstream", "rarity": "classified", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgposr-kLAtl7PDdTjlH_C5lhpKOk8j8NrrHjyVUupJy3uvErN732lC2rkVuZ2vwcYfGdgE4Yg7SqVO3yOnvjZO-787AznVg7ikms3ffnRfmhB9SLrs47VqY7kM/360fx360f", "price": 650},
            {"id": "ind_3", "weapon": "AK-47", "name": "Fire Serpent", "rarity": "covert", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot7HxfDhjxszJemkV08-5lpKKqPrxN7LEm1Rd6dd2j6eV94mi2lW3qkNoNzyicIfAdAc7YQzUqFC4yee50ZPpvJ2cnyNhvSUrs37VnBfmhB9SLrs47VqY7kM/360fx360f", "price": 2800},
            {"id": "ind_4", "weapon": "M4A1-S", "name": "Printstream", "rarity": "covert", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpou-6kejhz2v_Nfz5H_uO1gb-Gw_alIITBhGJf18l4jeHVu9in0FawqUU9YW7yI4_BdwQ4aV6D-QG6kOi5gsO77szPzCc26XYhsH-InhblgBhSLrs4Y4Wk5sM/360fx360f", "price": 3100},
            {"id": "ind_gold1", "weapon": "★ Butterfly Knife", "name": "Doppler (Phase 2)", "rarity": "extraordinary", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpovbSsLQJf0ebcZThQ6tCvq4GGqPr1Ibndk1RX6sl0te_S896ljAPiqERqazzzco-XJgc_N1yBqVO3kOvtgcDtvcicwSdlsyMjt37YnBW2hB4eO7RxxavJ4P0H0tM/360fx360f", "price": 8500},
            {"id": "ind_gold2", "weapon": "★ Karambit", "name": "Fade (100%)", "rarity": "extraordinary", "image": "https://community.cloudflare.steamstatic.com/economy/image/-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpovbSsLQJf2PLacDBA5ciJlY20k_jkI7fUhGJP68BAC-bb84mj3Fay-0toY27wcI6RdQE_Z1HW8wDvyebngcTt6cjImCdm7CU8pSGKqWp6b9w/360fx360f", "price": 9900}
        ]
    }
]

# Probabilities
# mil-spec: 54%, restricted: 24%, classified: 12%, covert: 7%, extraordinary: 3%
RARITY_WEIGHTS = {
    "mil-spec": 54,
    "restricted": 24,
    "classified": 12,
    "covert": 7,
    "extraordinary": 3
}

# ================= MATCHMAKING STATE =================
MATCHMAKING_QUEUES = {
    "1v1": [],
    "2v2": [],
    "5v5": [],
    "retakes": []
}

MATCHES_ACTIVE: Dict[str, Dict[str, Any]] = {}
PARTIES: Dict[str, Dict[str, Any]] = {}

MAPS_POOL = {
    "1v1": ["aim_map", "aim_redline", "aim_pistol_cs2", "aim_furious"],
    "2v2": ["de_inferno", "de_nuke", "de_overpass", "de_vertigo"],
    "5v5": ["de_mirage", "de_dust2", "de_inferno", "de_nuke", "de_ancient", "de_anubis"],
    "retakes": ["de_mirage", "de_dust2", "de_inferno"]
}

# ================= REQUEST SCHEMAS =================
class QueueJoinReq(BaseModel):
    mode: str = "5v5" # 1v1, 2v2, 5v5, retakes
    region: str = "EU-RO"

class PartyCreateReq(BaseModel):
    mode: str = "5v5"

class PartyJoinReq(BaseModel):
    code: str

class MatchAcceptReq(BaseModel):
    match_id: str

class MatchVetoReq(BaseModel):
    match_id: str
    map_name: str

class CaseOpenReq(BaseModel):
    case_id: str

class SkinSellReq(BaseModel):
    item_id: str

# ================= BUILD ARENA ROUTER =================
def build_arena_router(db, require_auth, get_user_optional):
    router = APIRouter(prefix="/arena", tags=["arena_matchmaking"])

    # ---------------- QUEUES & MATCHMAKING ----------------
    @router.get("/status")
    async def get_arena_status(user=Depends(get_user_optional)):
        """Returns active queues, player counts, live matches and current user state."""
        uid = user["id"] if user else None
        
        # Check if user is in a queue
        user_queue = None
        for q_mode, q_list in MATCHMAKING_QUEUES.items():
            for item in q_list:
                if item["user_id"] == uid:
                    user_queue = {"mode": q_mode, "joined_at": item["joined_at"], "elapsed_sec": int(time.time() - item["timestamp"])}
                    break
            if user_queue:
                break

        # Check if user is in an active match
        user_match = None
        if uid:
            for m_id, m in MATCHES_ACTIVE.items():
                if uid in m.get("player_ids", []):
                    user_match = m
                    break

        counts = {m: len(lst) for m, lst in MATCHMAKING_QUEUES.items()}
        total_queued = sum(counts.values())

        # Live matches summary
        live_list = [
            {
                "id": m["id"],
                "mode": m["mode"],
                "map": m["map"],
                "status": m["status"],
                "score_ct": m.get("score_ct", 0),
                "score_t": m.get("score_t", 0),
                "team1_name": m["team1_name"],
                "team2_name": m["team2_name"],
                "players_count": len(m.get("player_ids", []))
            }
            for m in list(MATCHES_ACTIVE.values())[-6:]
        ]

        return {
            "counts": counts,
            "total_queued": total_queued,
            "live_matches": live_list,
            "user_queue": user_queue,
            "user_match": user_match
        }

    @router.post("/queue/join")
    async def join_queue(body: QueueJoinReq, user=Depends(require_auth)):
        uid = user["id"]
        mode = body.mode if body.mode in MATCHMAKING_QUEUES else "5v5"

        # Remove from any existing queue
        for q_list in MATCHMAKING_QUEUES.values():
            q_list[:] = [x for x in q_list if x["user_id"] != uid]

        entry = {
            "user_id": uid,
            "user": {
                "id": uid,
                "username": user.get("username", "Player"),
                "avatar_url": user.get("avatar_url", ""),
                "loadout": user.get("loadout", {}),
                "elo": user.get("elo") or 1000,
                "rank": user.get("cs2_rank") or "Silver"
            },
            "joined_at": now_iso(),
            "timestamp": time.time(),
            "region": body.region
        }
        MATCHMAKING_QUEUES[mode].append(entry)

        # Trigger matchmaker check
        match_created = trigger_matchmaker_check(mode)
        
        return {
            "ok": True, 
            "mode": mode, 
            "position": len(MATCHMAKING_QUEUES[mode]),
            "match_created": match_created
        }

    @router.post("/queue/leave")
    async def leave_queue(user=Depends(require_auth)):
        uid = user["id"]
        for q_list in MATCHMAKING_QUEUES.values():
            q_list[:] = [x for x in q_list if x["user_id"] != uid]
        return {"ok": True, "message": "Left all queues"}

    def trigger_matchmaker_check(mode: str) -> Optional[Dict[str, Any]]:
        required = 2 if mode == "1v1" else (4 if mode == "2v2" else (10 if mode == "5v5" else 6))
        q_list = MATCHMAKING_QUEUES.get(mode, [])
        if len(q_list) < required:
            # Add realistic bots if queue is lonely to demonstrate instantly
            if len(q_list) >= 1:
                sample_bots = [
                    {"id": f"bot_{uuid.uuid4().hex[:6]}", "username": "s1mple_CS2", "avatar_url": "https://images.unsplash.com/photo-1566492031773-4f4e44671857?w=100", "loadout": {"avatar_frame": "frame_08.png", "username_style": "fireGlow"}, "elo": 1450, "rank": "Global Elite"},
                    {"id": f"bot_{uuid.uuid4().hex[:6]}", "username": "donk_aim", "avatar_url": "https://images.unsplash.com/photo-1535713875002-d1d0cf377fde?w=100", "loadout": {"avatar_frame": "frame_05.png", "username_style": "cityLights"}, "elo": 1500, "rank": "Global Elite"},
                    {"id": f"bot_{uuid.uuid4().hex[:6]}", "username": "NiKo_deagle", "avatar_url": "https://images.unsplash.com/photo-1570295999919-56ceb5ecca61?w=100", "loadout": {"avatar_frame": "frame_02.png", "username_style": "neonPink"}, "elo": 1380, "rank": "Supreme"},
                    {"id": f"bot_{uuid.uuid4().hex[:6]}", "username": "ZywOo_awp", "avatar_url": "https://images.unsplash.com/photo-1580489944761-15a19d654956?w=100", "loadout": {"avatar_frame": "frame_03.png", "username_style": "goldPulseAnimated"}, "elo": 1490, "rank": "Global Elite"},
                    {"id": f"bot_{uuid.uuid4().hex[:6]}", "username": "m0NESY_clutch", "avatar_url": "https://images.unsplash.com/photo-1628157582853-a796fa650a6a?w=100", "loadout": {"avatar_frame": "frame_08.png", "username_style": "emeraldFlow"}, "elo": 1420, "rank": "Supreme"},
                    {"id": f"bot_{uuid.uuid4().hex[:6]}", "username": "b1t_headshot", "avatar_url": "https://images.unsplash.com/photo-1522075469751-3a6694fb2f61?w=100", "loadout": {"avatar_frame": "frame_01.png", "username_style": "cyberGlitch"}, "elo": 1350, "rank": "Legendary Eagle"},
                    {"id": f"bot_{uuid.uuid4().hex[:6]}", "username": "ropz_lurker", "avatar_url": "https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=100", "loadout": {"avatar_frame": "frame_06.png", "username_style": "default"}, "elo": 1390, "rank": "Supreme"},
                    {"id": f"bot_{uuid.uuid4().hex[:6]}", "username": "jL_major", "avatar_url": "https://images.unsplash.com/photo-1500648767791-00dcc994a43e?w=100", "loadout": {"avatar_frame": "frame_07.png", "username_style": "cityLights"}, "elo": 1320, "rank": "Legendary Eagle"},
                    {"id": f"bot_{uuid.uuid4().hex[:6]}", "username": "flameZ_entry", "avatar_url": "https://images.unsplash.com/photo-1472099645785-5658abf4ff4e?w=100", "loadout": {"avatar_frame": "frame_04.png", "username_style": "fireGlow"}, "elo": 1300, "rank": "Master Guardian"}
                ]
                needed = required - len(q_list)
                for b_user in sample_bots[:needed]:
                    q_list.append({
                        "user_id": b_user["id"],
                        "user": b_user,
                        "joined_at": now_iso(),
                        "timestamp": time.time(),
                        "region": "EU-RO",
                        "is_bot": True
                    })

        matched_players = q_list[:required]
        MATCHMAKING_QUEUES[mode] = q_list[required:]

        match_id = uuid.uuid4().hex
        half = required // 2
        team1 = matched_players[:half]
        team2 = matched_players[half:]

        # Random map or first from pool
        chosen_map = random.choice(MAPS_POOL.get(mode, ["de_dust2"]))

        # Auto accept for bots
        accepted_dict = {p["user_id"]: True for p in matched_players if p.get("is_bot")}

        match_doc = {
            "id": match_id,
            "mode": mode,
            "status": "PENDING_ACCEPT", # PENDING_ACCEPT -> LIVE -> COMPLETED
            "created_at": now_iso(),
            "accept_deadline": (datetime.now(timezone.utc) + timedelta(seconds=25)).isoformat(),
            "accepted_players": accepted_dict,
            "player_ids": [p["user_id"] for p in matched_players],
            "team1": [p["user"] for p in team1],
            "team2": [p["user"] for p in team2],
            "team1_name": f"Team {team1[0]['user']['username']}",
            "team2_name": f"Team {team2[0]['user']['username']}",
            "map": chosen_map,
            "maps_pool": MAPS_POOL.get(mode, ["de_dust2", "de_mirage"]),
            "server_ip": "209.38.247.243",
            "server_port": random.choice([27015, 27016, 27017, 27018]),
            "server_password": f"ind_{random.randint(1000, 9999)}",
            "gotv_port": 27020,
            "score_ct": 0,
            "score_t": 0,
            "rounds_history": [],
            "stats": {p["user_id"]: {"kills": 0, "deaths": 0, "assists": 0, "mvps": 0, "adr": 0} for p in matched_players}
        }

        MATCHES_ACTIVE[match_id] = match_doc
        return match_doc

    # ---------------- MATCH CONTROLS ----------------
    @router.get("/matches/{match_id}")
    async def get_match_details(match_id: str):
        match = MATCHES_ACTIVE.get(match_id)
        if not match:
            # Look in db historical matches
            match = await db.idg_matches.find_one({"id": match_id}, {"_id": 0})
            if not match:
                raise HTTPException(404, "Match not found")
        return match

    @router.post("/matches/{match_id}/accept")
    async def accept_match(match_id: str, user=Depends(require_auth)):
        uid = user["id"]
        match = MATCHES_ACTIVE.get(match_id)
        if not match:
            raise HTTPException(404, "Match not found")

        match["accepted_players"][uid] = True
        
        # Check if all players accepted
        total_req = len(match["player_ids"])
        accepted_count = len(match["accepted_players"])

        if accepted_count >= total_req:
            match["status"] = "LIVE"
            match["started_at"] = now_iso()

        return {
            "ok": True,
            "accepted_count": accepted_count,
            "total_req": total_req,
            "status": match["status"]
        }

    @router.post("/matches/{match_id}/simulate-round")
    async def simulate_round(match_id: str, user=Depends(require_auth)):
        """Allows testing & live updates of round events."""
        match = MATCHES_ACTIVE.get(match_id)
        if not match:
            raise HTTPException(404, "Match not found")

        # Give random point to team 1 or team 2
        winner = random.choice(["team1", "team2"])
        if winner == "team1":
            match["score_ct"] += 1
        else:
            match["score_t"] += 1

        # Pick random MVP
        mvp_player = random.choice(match["team1"] if winner == "team1" else match["team2"])
        match["rounds_history"].append({
            "round": match["score_ct"] + match["score_t"],
            "winner": winner,
            "mvp": mvp_player["username"]
        })

        # Update stats
        for pid in match["player_ids"]:
            match["stats"][pid]["kills"] += random.randint(0, 3)
            match["stats"][pid]["deaths"] += random.randint(0, 1)

        # Check match point
        max_rounds = 13 if match["mode"] in ["5v5", "2v2"] else 9
        if match["score_ct"] >= max_rounds or match["score_t"] >= max_rounds:
            match["status"] = "COMPLETED"
            match["ended_at"] = now_iso()
            match["winner_team"] = "team1" if match["score_ct"] > match["score_t"] else "team2"
            
            # Save to permanent history
            await db.idg_matches.insert_one(dict(match))

        return match

    # ---------------- CASE OPENING & SKINS ECONOMY ----------------
    @router.get("/cases")
    async def list_cases():
        return CASES_CATALOG

    @router.post("/cases/open")
    async def open_case(body: CaseOpenReq, user=Depends(require_auth)):
        case_def = next((c for c in CASES_CATALOG if c["id"] == body.case_id), None)
        if not case_def:
            raise HTTPException(404, "Case not found")

        # Check user points
        user_doc = await db.users.find_one({"id": user["id"]})
        current_points = user_doc.get("points", 0) if user_doc else 0

        if current_points < case_def["price"]:
            raise HTTPException(400, f"Puncte insuficiente. Ai nevoie de {case_def['price']} pct (Ai: {current_points} pct).")

        # Deduct points
        await db.users.update_one({"id": user["id"]}, {"$inc": {"points": -case_def["price"]}})
        await db.points_log.insert_one({
            "id": uuid.uuid4().hex,
            "user_id": user["id"],
            "amount": -case_def["price"],
            "reason": f"Case Opening: {case_def['name']}",
            "created_at": now_iso()
        })

        # Weighted roll
        # Mil-Spec 54%, Restricted 24%, Classified 12%, Covert 7%, Extraordinary 3%
        roll_num = random.uniform(0, 100)
        if roll_num < 3:
            picked_rarity = "extraordinary"
        elif roll_num < 10:
            picked_rarity = "covert"
        elif roll_num < 22:
            picked_rarity = "classified"
        elif roll_num < 46:
            picked_rarity = "restricted"
        else:
            picked_rarity = "mil-spec"

        matching_skins = [s for s in case_def["skins"] if s["rarity"] == picked_rarity]
        if not matching_skins:
            matching_skins = case_def["skins"]

        winning_skin = random.choice(matching_skins)

        # Generate 56-reel tape for physical unboxing animation
        reel_items = []
        for i in range(56):
            if i == 43: # Winning Slot
                reel_items.append(winning_skin)
            else:
                reel_items.append(random.choice(case_def["skins"]))

        # Store in user inventory
        inventory_item = {
            "id": uuid.uuid4().hex,
            "user_id": user["id"],
            "case_id": case_def["id"],
            "case_name": case_def["name"],
            "skin": winning_skin,
            "unboxed_at": now_iso(),
            "status": "in_inventory"
        }
        await db.idg_user_skins.insert_one(inventory_item)
        inventory_item.pop("_id", None)

        return {
            "ok": True,
            "winning_skin": winning_skin,
            "winning_slot": 43,
            "reel": reel_items,
            "inventory_item": inventory_item,
            "remaining_points": current_points - case_def["price"]
        }

    @router.get("/inventory")
    async def get_user_inventory(user=Depends(require_auth)):
        cursor = db.idg_user_skins.find({"user_id": user["id"], "status": "in_inventory"}, {"_id": 0}).sort("unboxed_at", -1)
        items = await cursor.to_list(100)
        return items

    @router.post("/inventory/sell")
    async def sell_skin(body: SkinSellReq, user=Depends(require_auth)):
        item = await db.idg_user_skins.find_one({"id": body.item_id, "user_id": user["id"], "status": "in_inventory"})
        if not item:
            raise HTTPException(404, "Skin-ul nu a fost găsit în inventar.")

        sell_price = item["skin"].get("price", 50)

        # Remove from inventory
        await db.idg_user_skins.update_one({"id": body.item_id}, {"$set": {"status": "sold", "sold_at": now_iso()}})

        # Credit user points
        await db.users.update_one({"id": user["id"]}, {"$inc": {"points": sell_price}})
        await db.points_log.insert_one({
            "id": uuid.uuid4().hex,
            "user_id": user["id"],
            "amount": sell_price,
            "reason": f"Vânzare Skin: {item['skin']['weapon']} | {item['skin']['name']}",
            "created_at": now_iso()
        })

        return {"ok": True, "awarded_points": sell_price, "message": f"Skin vândut cu succes pentru {sell_price} puncte!"}

    # ---------------- ARENA LEADERBOARD ----------------
    @router.get("/leaderboard")
    async def arena_leaderboard(limit: int = 15):
        users = await db.users.find(
            {"username": {"$not": {"$regex": "^TEST_", "$options": "i"}}},
            {"_id": 0, "id": 1, "username": 1, "avatar_url": 1, "loadout": 1, "is_vip": 1, "vip_tier": 1, "role": 1, "points": 1, "elo": 1, "cs2_rank": 1}
        ).sort("points", -1).limit(limit).to_list(limit)

        for idx, u in enumerate(users):
            u["elo"] = u.get("elo") or (1200 + (len(users) - idx) * 45)
            u["rank"] = u.get("cs2_rank") or ("Global Elite" if idx == 0 else ("Supreme" if idx < 3 else "Master Guardian"))
            u["matches_won"] = max(5, int((u.get("points", 100) / 40)))
            u["winrate"] = f"{min(88, 55 + idx * 2)}%"

        return users

    return router
