import pandas as pd
import numpy as np
from ParaUtils import parse_WPS_rankings
from ParaUtils.Standards import LA2028_Events
from ParaUtils.AWR import set_AWR

from pathlib import Path
module_dir = Path(__file__).parent

ML = (
    pd.read_excel(module_dir / '2025_10_07 World Para Swimming Online Classification Master List.xlsx',header=8)
    .pipe(lambda df: df.rename(columns={c:c.replace(' ','_') for c in df.columns}))
    .rename(columns={'ID':'SDMS_ID'})
    .loc[:,'NPC Given_Name Family_Name SDMS_ID Gender S SB SM'.split()]
    .assign(S=lambda df: df.S.apply(lambda S: int(''.join([c for c in '0'+str(S) if c.isdigit()]))))
    .assign(SB=lambda df: df.SB.apply(lambda S: int(''.join([c for c in '0'+str(S) if c.isdigit()]))))
    .assign(SM=lambda df: df.SM.apply(lambda S: int(''.join([c for c in '0'+str(S) if c.isdigit()]))))
)

AWR = parse_WPS_rankings(pd.read_excel(module_dir / '2025_10_07 World Para Swimming Online Rankings.xlsx',header=8))
AWR = (
    AWR
    .pipe(lambda df: df.rename(columns={c:c.replace(' ','_') for c in df.columns}))
    
    #Update SportClass with MasterList Info
    .merge(ML['SDMS_ID S SB SM'.split()],on='SDMS_ID',how='inner')
    .assign(Category=lambda df: df.Stroke.apply(lambda S: {'Breaststroke':'SB','Medley':'SM'}.get(S,'S')))
    .groupby('Category',group_keys=False)
    .apply(lambda df: df.assign(SportClass=df.loc[:,df.Category.values[0]]))
    
    #Group by LA2028 Events
    .merge(LA2028_Events,on='Gender SportClass Stroke Distance'.split(),how='inner')
    
    #Rank by NPC
    .groupby('Gender EventClass Stroke Distance NPC'.split(),group_keys=False)
    .apply(lambda df: df.assign(NPC_Rank=df.Seconds.apply(lambda S: 1+len(df[df.Seconds < S]))))
    
    #Set AWR, 3 per NPC excluding Canadians
    .groupby('Gender EventClass Stroke Distance'.split(),group_keys=False)
    .apply(set_AWR)
    
    #Set 2/3 threshold for DEV Cards
    .groupby('Gender EventClass Stroke Distance'.split(),group_keys=False)
    .apply(lambda df: df.assign(TopTwoThirds=int(np.floor(len(df)*2/3))))
    
    #Sort
    .sort_values('Gender Stroke Distance EventClass Seconds AWR'.split())
)