import os,time
from urllib.parse import quote
import httpx
ROUTES={'EUW1':'europe','EUN1':'europe','TR1':'europe','RU':'europe','ME1':'europe','NA1':'americas','BR1':'americas','LA1':'americas','LA2':'americas','KR':'asia','JP1':'asia','OC1':'sea','SG2':'sea','TW2':'sea','VN2':'sea','PH2':'sea','TH2':'sea'}
class RiotError(Exception):pass
class Riot:
    def __init__(self):
        key=os.getenv('RIOT_API_KEY','')
        if not key:raise RiotError('کلید Riot روی سرور تنظیم نشده است؛ از مدیر پیگیری کنید.')
        self.client=httpx.Client(timeout=25,headers={'X-Riot-Token':key})
    def close(self):self.client.close()
    def get(self,region,path,params=None):
        for attempt in range(4):
            try:r=self.client.get(f'https://{region}.api.riotgames.com{path}',params=params)
            except httpx.RequestError:
                if attempt==3:raise RiotError('ارتباط با Riot برقرار نشد؛ بعداً تلاش کنید.')
                time.sleep(2);continue
            if r.status_code==429:
                wait=min(60,max(1,int(r.headers.get('Retry-After','5'))))
                if attempt==3:raise RiotError('محدودیت درخواست Riot؛ چند دقیقه بعد تلاش کنید.')
                time.sleep(wait);continue
            if r.status_code==404:raise RiotError('اکانت یا داده یافت نشد؛ Riot ID و سرور را بررسی کنید.')
            if r.status_code in (401,403):raise RiotError('کلید Riot نامعتبر، منقضی یا فاقد مجوز است.')
            if r.status_code>=500 and attempt<3:time.sleep(2);continue
            if r.status_code!=200:raise RiotError(f'دریافت داده از Riot ناموفق بود ({r.status_code}).')
            return r.json()
        raise RiotError('دریافت داده ناموفق بود.')
    def history(self,riot_id,platform,count=20):
        region=ROUTES[platform];name,tag=riot_id.rsplit('#',1)
        a=self.get(region,f'/riot/account/v1/accounts/by-riot-id/{quote(name,safe="")}/{quote(tag,safe="")}');puuid=a['puuid']
        ids=self.get(region,f'/lol/match/v5/matches/by-puuid/{quote(puuid,safe="")}/ids',{'start':0,'count':min(count,30),'type':'ranked'})
        games=[]
        for mid in ids:
            info=self.get(region,f'/lol/match/v5/matches/{mid}')['info']
            if info.get('mapId')!=11 or info.get('gameDuration',0)<300:continue
            p=next((p for p in info['participants'] if p['puuid']==puuid),None)
            if not p:continue
            team=[x for x in info['participants'] if x['teamId']==p['teamId']]
            dur=info['gameDuration']/60;tk=sum(x['kills'] for x in team)
            games.append({'id':mid,'champion':p['championName'],'role':p.get('teamPosition') or 'UNKNOWN','win':p['win'],'kills':p['kills'],'deaths':p['deaths'],'assists':p['assists'],'cs':round((p.get('totalMinionsKilled',0)+p.get('neutralMinionsKilled',0))/dur,2),'vision':round(p.get('visionScore',0)/dur,2),'kp':round((p['kills']+p['assists'])/tk*100,1) if tk else 0,'minutes':round(dur,1),'patch':'.'.join(info['gameVersion'].split('.')[:2]),'date':info.get('gameStartTimestamp',0),'enemies':[x['championName'] for x in info['participants'] if x['teamId']!=p['teamId']]})
            time.sleep(.12)
        return {'riot_id':riot_id,'platform':platform,'games':games,'fetched':int(time.time())}
