from fastapi import APIRouter, Depends, HTTPException, Request
from pydantic import BaseModel
from typing import Dict, Any, Optional
import os
import aiohttp
from datetime import datetime, timezone

router = APIRouter(prefix="/stats", tags=["Faceit API Integration"])

FACEIT_API_KEY = os.getenv("FACEIT_API_KEY", "")

# We need the user's auth logic, we can reuse it from server.py but since we are in an external router,
# we can define a dependency that expects the request object.
async def get_current_user_from_request(request: Request):
    auth = request.headers.get("Authorization", "")
    if not auth.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="Unauthorized")
    token = auth[7:]
    import jwt
    JWT_SECRET = os.environ.get('JWT_SECRET', '')
    try:
        payload = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])
        user = await request.app.state.db.users.find_one({"id": payload["sub"]})
        if not user:
            raise HTTPException(status_code=401, detail="User not found")
        return user
    except Exception:
        raise HTTPException(status_code=401, detail="Invalid token")

class LinkFaceitRequest(BaseModel):
    faceit_nickname: str

@router.post("/link-faceit")
async def link_faceit_account(req: LinkFaceitRequest, request: Request, user = Depends(get_current_user_from_request)):
    """Links a Faceit account to the INDUNGI profile."""
    nickname = req.faceit_nickname.strip()
    if not nickname:
        raise HTTPException(status_code=400, detail="Nickname cannot be empty")
        
    db = request.app.state.db
    
    # 1. Fetch Faceit ID using the nickname
    # In a real scenario with API Key:
    if FACEIT_API_KEY:
        try:
            async with aiohttp.ClientSession() as session:
                headers = {"Authorization": f"Bearer {FACEIT_API_KEY}"}
                async with session.get(f"https://open.faceit.com/data/v4/players?nickname={nickname}", headers=headers) as resp:
                    if resp.status == 200:
                        data = await resp.json()
                        faceit_id = data.get("player_id")
                        faceit_avatar = data.get("avatar")
                    else:
                        raise HTTPException(status_code=400, detail="Faceit account not found")
        except Exception as e:
            raise HTTPException(status_code=400, detail="Failed to connect to Faceit API")
    else:
        # Fallback Mock logic for development
        faceit_id = f"faceit-mock-{nickname}"
        faceit_avatar = ""
        
    # 2. Save to user profile
    await db.users.update_one(
        {"id": user["id"]},
        {"$set": {
            "faceit_id": faceit_id,
            "faceit_nickname": nickname,
            "faceit_avatar": faceit_avatar
        }}
    )
    
    return {"message": "Contul de FACEIT a fost sincronizat cu succes!", "faceit_id": faceit_id}

@router.get("/{username}/cs2")
async def get_cs2_stats(username: str, request: Request):
    """Fetches real CS2 stats from Faceit for a given user."""
    db = request.app.state.db
    user = await db.users.find_one({"username": username})
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
        
    faceit_id = user.get("faceit_id")
    if not faceit_id:
        return {"linked": False, "message": "User has not linked a Faceit account."}
        
    stats = {
        "linked": True,
        "faceit_nickname": user.get("faceit_nickname"),
        "elo": 0,
        "skill_level": 1,
        "matches_played": 0,
        "win_rate": "0%",
        "avg_kd": "0.00",
        "avg_headshots": "0%",
        "recent_matches": []
    }
    
    if FACEIT_API_KEY and not faceit_id.startswith("faceit-mock-"):
        try:
            async with aiohttp.ClientSession() as session:
                headers = {"Authorization": f"Bearer {FACEIT_API_KEY}"}
                # 1. Fetch player details (ELO, Level)
                async with session.get(f"https://open.faceit.com/data/v4/players/{faceit_id}", headers=headers) as resp:
                    if resp.status == 200:
                        data = await resp.json()
                        cs2_game = data.get("games", {}).get("cs2", {})
                        stats["elo"] = cs2_game.get("faceit_elo", 0)
                        stats["skill_level"] = cs2_game.get("skill_level", 1)
                
                # 2. Fetch global CS2 stats (Win rate, K/D, Headshots)
                async with session.get(f"https://open.faceit.com/data/v4/players/{faceit_id}/stats/cs2", headers=headers) as resp:
                    if resp.status == 200:
                        data = await resp.json()
                        lifetime = data.get("lifetime", {})
                        stats["matches_played"] = lifetime.get("Matches", "0")
                        stats["win_rate"] = lifetime.get("Win Rate %", "0") + "%"
                        stats["avg_kd"] = lifetime.get("Average K/D Ratio", "0.00")
                        stats["avg_headshots"] = lifetime.get("Average Headshots %", "0") + "%"
                
                # 3. Fetch match history (Last 5)
                async with session.get(f"https://open.faceit.com/data/v4/players/{faceit_id}/history?game=cs2&offset=0&limit=5", headers=headers) as resp:
                    if resp.status == 200:
                        data = await resp.json()
                        matches = []
                        for m in data.get("items", []):
                            # To get detailed K/D per match, you need to call /matches/{match_id}/stats
                            # For simplicity, we just extract W/L and score here
                            results = m.get("results", {})
                            faction_won = results.get("winner")
                            my_faction = "faction1" if m.get("teams", {}).get("faction1", {}).get("roster", [{}])[0].get("player_id") == faceit_id else "faction2" # Simplification
                            
                            is_win = faction_won == my_faction
                            
                            matches.append({
                                "id": m.get("match_id"),
                                "map": "Unknown Map", # Usually requires match details fetch
                                "result": "W" if is_win else "L",
                                "score": f"{results.get('score', {}).get('faction1', 0)}-{results.get('score', {}).get('faction2', 0)}",
                                "date": datetime.fromtimestamp(m.get("finished_at", 0), timezone.utc).isoformat(),
                                "kd": "N/A"
                            })
                        stats["recent_matches"] = matches
                        
        except Exception as e:
            print("Faceit API Error:", e)
            # Proceed with whatever data we fetched
    else:
        # Mock Response matching the UI requirements
        stats.update({
            "elo": 2150,
            "skill_level": 10,
            "matches_played": 342,
            "win_rate": "54%",
            "avg_kd": "1.24",
            "avg_headshots": "48%",
            "recent_matches": [
                {"id": "m1", "map": "de_mirage", "result": "W", "score": "13-10", "date": datetime.now(timezone.utc).isoformat(), "kd": "1.45"},
                {"id": "m2", "map": "de_inferno", "result": "L", "score": "9-13", "date": datetime.now(timezone.utc).isoformat(), "kd": "0.89"},
                {"id": "m3", "map": "de_vertigo", "result": "W", "score": "13-11", "date": datetime.now(timezone.utc).isoformat(), "kd": "1.12"},
            ]
        })
        
    return stats
