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

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

fnames = ['Rankings 2023.xlsx','Rankings 2024.xlsx','Rankings 2025 2025-04-02.xlsx']
raw = (
    pd.concat([
        pd.read_excel(module_dir / fname,header=8)
        for fname in fnames
    ])
    .pipe(lambda df: parse_WPS_rankings(df))

    #best results per athlete regardless of sportclass at performance
    .sort_values('Seconds')
    .groupby('SDMS_ID Stroke Distance'.split())
    .head(1)
    
    #select columns
    .pipe(lambda df: df['Gender SportClass Distance Stroke Result Seconds SDMS_ID NPC Given_Name Family_Name Date'.split()])
    
    #set helper column Cat
    .assign(Cat=lambda df: df.Stroke.apply(lambda S: {'Breaststroke':'SB','Medley':'SM'}.get(S,'S')))
)

ML = (
    pd.concat([
        pd.read_excel(module_dir / 'Masterlist 2024.xlsx',header=8).assign(Year=2024),
        pd.read_excel(module_dir / 'Masterlist 2025 2025-04-02.xlsx',header=8).assign(Year=2025),
    ])
    .reset_index(drop=True)
    .pipe(lambda df: df.rename(columns={c:c.replace(' ','_') for c in df.columns}))
    .rename(columns={'ID':'SDMS_ID','Status':'Status_S','Status.1':'Status_SB','Status.2':'Status_SM'})
    .sort_values('Year')
    .groupby('SDMS_ID')
    .tail(1)
    .pipe(lambda df: df['SDMS_ID Year S SB SM Status_S Status_SB Status_SM'.split()])
    .assign(Helper=lambda df: df.Status_S.astype(str).str.upper().str.contains('N') | df.Status_SB.astype(str).str.upper().str.contains('N') | df.Status_SM.astype(str).str.upper().str.contains('N'))
    .pipe(lambda df: df[~df.Helper])
    .melt(id_vars='Helper SDMS_ID Year'.split())
    .pipe(lambda df: df[~df.value.isin('NE CNC'.split())])
    .dropna()
    .assign(Cat=lambda df: df.variable.apply(lambda S: S.split('_')[-1]))
    .assign(Type=lambda df: df.variable.replace('S','SportClass_S').replace('SB','SportClass_SB').replace('SM','SportClass_SM').apply(lambda S: S.split('_')[0]))
    .pipe(lambda df: pd.pivot_table(df,index='SDMS_ID Year Cat'.split(),columns='Type',values='value',aggfunc=min))
    .dropna()
    .reset_index()
    .assign(SportClass=lambda df: df.SportClass.apply(lambda S: int(''.join([c for c in str(S) if c.isdigit()]))))
    .drop('Status',axis=1)
    .pipe(lambda df: pd.concat([df,(
        raw
        .pipe(lambda df: df[df.Date.dt.year == 2023])
        .assign(Year=2023)
        .pipe(lambda df: df['SDMS_ID Year Cat SportClass'.split()])
    )]))
    .sort_values('Year')
    .groupby('SDMS_ID Cat'.split())
    .tail(1)
)

AWR = (
    raw

    #set sportclass to most recent ML or results from 2023
    .merge(ML,on='SDMS_ID Cat'.split(),how='inner')
    .drop('SportClass_x',axis=1)
    .rename(columns={'SportClass_y':'SportClass'})
    
    #filter to 2025 WC events including swimups
    .merge(WC2025_Events,on='Gender SportClass Stroke Distance'.split(),how='inner')
    
    #best performance per event per swimmer per eventclass
    .sort_values('Seconds')
    .groupby('SDMS_ID EventClass Stroke Distance'.split())
    .head(1)
    
    #set National Rankings
    .groupby('NPC Gender EventClass Stroke Distance'.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 country, no Canadians
    .groupby('Gender EventClass Stroke Distance'.split(),group_keys=False)
    .apply(set_AWR)
    .sort_values('Gender Stroke Distance SportClass Seconds'.split())
)