from pyodide_http import patch_all
import numpy as np
import pandas as pd
from pyscript import document, display, when

patch_all()

@when("click", "#js-formButton")
def CalculateAntei(event):

    n1 = document.querySelector("#num1").value
    n2 = document.querySelector("#num2").value
    n3 = document.querySelector("#num3").value
    n4 = document.querySelector("#num4").value

    try:
        n1 = int(n1)
        n2 = int(n2)
        n3 = int(n3)
        n4 = int(n4)

        def draw_posterior(
            n1 : int,
            n2 : int,
            n3 : int,
            n4 : int,
            alpha: np.ndarray = np.array([200, 200, 200, 200]),
            n_draws: int = 500000,
            ) -> pd.DataFrame:
        
            total_games = n1 + n2 + n3 + n4
            p = np.array([n1/total_games, n2/total_games, n3/total_games, n4/total_games])
    
            df = pd.DataFrame(
                np.random.dirichlet(alpha + p * total_games, size=n_draws),
                columns=["1位率", "2位率", "3位率", "4位率"],
            )
            df["平均順位"] = df.values @ np.array([1, 2, 3, 4])
            df["安定段位"] = 7 + ((90 * df["1位率"] + 45 * df["2位率"]) / df["4位率"] - 135) / 15
    
            return df

        def run_draw_posterior(n1: int, n2: int, n3: int, n4: int) -> pd.DataFrame:
            return draw_posterior(n1, n2, n3, n4)
        
        def get_confidence_interval(df: pd.DataFrame) -> pd.DataFrame:
            lower_bound = df.quantile(0.025)
            upper_bound = df.quantile(0.975)
            median_bound = df.quantile(0.5)
            confidence_interval = pd.concat([pd.Series(lower_bound), pd.Series(upper_bound), pd.Series(median_bound)], axis=1)
            confidence_interval.columns = ["Lower Bound", "Upper Bound", "Median"]
            return confidence_interval
        
        result = run_draw_posterior(n1, n2, n3, n4)                
        confidence_interval = get_confidence_interval(result["安定段位"])

        def mikake_antei(n1:int, n2:int, n3:int, n4:int):
            mikake = mikake = 7 + ((90 * n1 + 45 * n2) / n4 - 135) / 15
            return mikake

        total_games = n1 + n2 + n3 + n4

        mikake = round(mikake_antei(n1, n2, n3, n4), 4)
        estimateMin = round(confidence_interval.iloc[0, 0], 4)
        estimateMax = round(confidence_interval.iloc[0, 1], 4)
        estimateMed = round(confidence_interval.iloc[0, 2], 4)

        display(mikake, target="py-antei", append=False)
        display(estimateMed, target="py-median", append=False)
        display(estimateMin, target="py-estimationMin", append=False)
        display(estimateMax, target="py-estimationMax", append=False)
        display(total_games, target="py-totalgames", append=False)

        if total_games >= 10000:
            if estimateMin >= 8:
                if estimateMed >= 8.65:
                    text = "神"
                else: 
                    text = "超鉄強"
            elif 7.75 <= estimateMin < 8:
                text = "超鉄強"
            elif 7.5 <= estimateMin < 7.75:
                text = "鉄強"
            elif 7 <= estimateMin < 7.5:
                if estimateMed >= 8:
                    text = "鳳凰の達人"
                else:
                    text = "鳳凰の主"
            elif estimateMin < 7:
                if estimateMed >= 7.3:
                    text = "ベテラン鳳凰民"
                elif 7 <= estimateMed < 7.3:
                    text = "鳳凰の熟練兵"
                else:
                    text = "鳳凰の修行僧"
        elif 3000 <= total_games < 10000:
            if estimateMin >= 8:
                if estimateMed >= 8.65:
                    text = "神"
                else: 
                    text = "超鉄強"
            elif 7.75 <= estimateMin < 8:
                text = "超鉄強"
            elif 7.5 <= estimateMin < 7.75:
                text = "鉄強"
            elif 7 <= estimateMin < 7.5:
                if estimateMed >= 8:
                    text = "鳳凰の達人"
                else:
                    text = "鳳凰の猛者"
            elif estimateMin < 7:
                if estimateMed >= 7.6:
                    text = "鳳凰の強者"
                elif 7.3 <= estimateMed < 7.6:
                    text = "The 鳳凰民"
                elif 7 <= estimateMed < 7.3:
                    text = "豆鳳"
                else:
                    text = "鳳凰の修行僧"
        elif 1000 <= total_games < 3000:
            if estimateMin >= 8:
                if estimateMed >= 8.65:
                    text = "神"
                else: 
                    text = "超鉄強"
            elif 7.75 <= estimateMin < 8:
                text = "超鉄強"
            elif 7.5 <= estimateMin < 7.75:
                text = "鉄強"
            elif 7 <= estimateMin < 7.5:
                if estimateMed >= 8:
                    text = "鳳凰の達人"
                else:
                    text = "鳳凰の猛者"
            elif estimateMin < 7:
                if estimateMed >= 7.6:
                    text = "鳳凰の強者"
                elif 7.3 <= estimateMed < 7.6:
                    text = "The 鳳凰民"
                elif 7 <= estimateMed < 7.3:
                    text = "豆鳳"
                else:
                    text = "鳳凰の挑戦者"
        elif total_games < 1000:
            if estimateMin >= 8:
                if estimateMed >= 8.65:
                    text = "神"
                else: 
                    text = "超鉄強"
            elif 7.75 <= estimateMin < 8:
                text = "超鉄強"
            elif 7.5 <= estimateMin < 7.75:
                text = "鉄強"
            elif 7 <= estimateMin < 7.5:
                if estimateMed >= 8:
                    text = "鳳凰の達人"
                else:
                    text = "鳳凰の猛者"
            elif estimateMin < 7:
                if estimateMed >= 7.6:
                    text = "鳳凰の強者"
                elif 7.3 <= estimateMed < 7.6:
                    text = "The 鳳凰民"
                elif 7 <= estimateMed < 7.3:
                    text = "豆鳳"
                else:
                    text = "鳳凰のひよこ"
    
        display(text, target="py-estimationText", append=False)

    except ValueError:
        display("正しい数値を入力してください", target="py-errorText", append=False)
        return