import directory
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
from math import pi
import scipy.stats as st
import plotly.graph_objects as go
from PIL import Image
import os

path1 = os.path.join(directory.FONT_DIR, 'Pretendard-SemiBold.ttf')
fontprop_semibold = fm.FontProperties(fname=path1)
path2 = os.path.join(directory.FONT_DIR, 'Pretendard-Bold.ttf')
fontprop_bold = fm.FontProperties(fname=path2)
path3 = os.path.join(directory.FONT_DIR, 'Font Awesome 6 Free-Solid-900.otf')
fontprop_awesome = fm.FontProperties(fname=path3)
BASE_DIR = directory.BASE_DIR

def plot_EEG_ebsi_radar(values: list, RESULT_DIR: str):
    """
    plot EEG EBSI radar chart
    Args:
        values (list) : ['Foggy', 'Talented', 'Tense',  'Mindful'] # 안개형, 영재형, 긴장형, 차분형
        RESULT_DIR (str) : RESULT_DIR
    """
    values += values[:1]  # Because of the circulating Radar Chart personality.
    N = len(values) - 1
    angles = [n / float(N) * 2 * pi for n in range(N)]
    angles += angles[:1]

    plt.figure(figsize=(7, 6))
    ax = plt.subplot(111, polar=True)

    ax.yaxis.grid(linewidth=1, linestyle='--', color='#BFBFBF')
    ax.grid(alpha=0.7)
    ax.tick_params(axis='x', which='major', pad=25, labelsize=15)
    ax.set_rlabel_position(0)
    ax.scatter(angles, values, color='#1754A5', s=20)
    ax.plot(angles, values, color='#1754A5', linewidth=2, linestyle='solid')  # Plot data
    ax.fill(angles, values, color='#0084E1', alpha=0.2)  # Fill area

    circle = plt.Circle((0, 0), 100, transform=ax.transData._b, fill=False, edgecolor='#7D7D7D', linewidth=5, zorder=10)
    plt.gca().add_artist(circle)

    plt.ylim(0, 100)
    xticks = [" ", " ", " ", " "]
    plt.xticks(angles[:-1], xticks, color='black', size=15)
    plt.yticks(alpha=0.3, size=14)
    plt.savefig(os.path.join(RESULT_DIR, "eeg_ebsi_radar.png"), dpi=300)


def plot_PPG_ebsi_radar(values: list, RESULT_DIR: str):
    """
    plot PPG EBSI radar chart
    Args:
        values (list) : [Mind Weak, Depress, Anxious] # 심약형, 우울형, 불안형
        RESULT_DIR (str) : RESULT_DIR
    """
    values += values[:1]  # Because of the circulating Radar Chart personality.
    N = len(values) - 1
    angles = [n / float(N) * 2 * pi for n in range(N)]
    angles += angles[:1]

    plt.figure(figsize=(7, 6))
    ax = plt.subplot(111, polar=True)

    ax.yaxis.grid(linewidth=1, linestyle='--', color='#BFBFBF')
    ax.grid(alpha=0.7)
    ax.tick_params(axis='x', which='major', pad=25, labelsize=15)
    ax.set_rlabel_position(0)
    ax.scatter(angles, values, color='#1754A5', s=20)
    ax.plot(angles, values, color='#1754A5', linewidth=2, linestyle='solid')  # Plot data
    ax.fill(angles, values, color='#0084E1', alpha=0.2)  # Fill area

    circle = plt.Circle((0, 0), 100, transform=ax.transData._b, fill=False, edgecolor='#7D7D7D', linewidth=5, zorder=10)
    plt.gca().add_artist(circle)

    plt.ylim(0, 100)
    xticks = [" ", " ", " "]
    plt.xticks(angles[:-1], xticks, color='black', size=15)
    plt.yticks(alpha=0.3, size=14)
    plt.savefig(os.path.join(RESULT_DIR, "ppg_ebsi_radar.png"), dpi=300)


def plot_score(score: int, sort: str, RESULT_DIR: str, reportLanguage: str="kr"):
    '''
    plot brain acitivity bar plot
    Args:
        score (int) : Maumgyeol Score
        sort (str) : eeg or ppg
        RESULT_DIR (str) : RESULT_DIR
    '''
    fig, ax = plt.subplots(figsize=(6, 6))
    ax = plt.subplot(projection='polar')
    data = [100, score]
    startangle = 90
    colors = ['#121CA7', '#0053CC']
    xs = [(i * pi * 2) / 100 for i in data]
    ys = [1, 1]
    left = (startangle * pi * 2) / 360  # this is to control where the bar starts

    # plot bars and points at the end to make them round
    ax.bar(10 * 2 * np.pi / 100, -4, width=2 * np.pi, color='#AAD2E6', edgecolor=None, alpha=0.2)
    ax.bar(10 * 2 * np.pi / 100, 1, width=2 * np.pi, color='#AAD2E6', edgecolor=None, alpha=0.2)
    ax.barh(ys[1], xs[1], left=left, height=0.8, color=colors[1], alpha=1, zorder=2)
    ax.barh(ys[0], xs[0], left=left, height=0.2, color=colors[0], alpha=0.2)
    ax.scatter(xs[1] + left, ys[1] - 0.005, s=250, color=colors[1], zorder=2)
    ax.scatter(left + 0.003, ys[1] + 0.005, s=250, color=colors[1], zorder=2)

    ax.fill(ys, xs, 'red')

    plt.ylim(-4, 4)
    if reportLanguage =="en":
        plt.text(-1.5, -3.5, score, ha='center', va='center', fontsize=90, fontproperties=fontprop_semibold)
    else:
        plt.text((10 * pi * 2)/ 100, -4, score, ha='center', va='center', fontsize=90, fontproperties=fontprop_semibold)
        plt.text(-1.54, -1.8, "점", ha='center', va='center', fontsize=25, fontproperties=fontprop_bold, color='#7D7D7D', alpha=0.6)

    plt.xticks([])
    plt.yticks([])
    ax.spines.clear()
    plt.savefig(os.path.join(RESULT_DIR, sort + '_score.png'), dpi=300)


def plot_brain_activity(values: list, RESULT_DIR: str):
    '''
    plot brain acitivity bar plot
    Args:
        values (list) : ['θ', 'Lα', 'Hα', 'Lβ', 'Mβ', 'Hβ', 'γ'], percent format
        RESULT_DIR (str) : RESULT_DIR
    '''

    plt.figure(figsize=(6.7, 7.8))  # 7:5비율로
    ax = plt.gca()
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)

    x = ['θ', 'Lα', 'Hα', 'Lβ', 'Mβ', 'Hβ', 'γ']
    colors = ['#0084E1', '#FFC200', '#F94C56', '#EA89E3', '#00BD53', '#9072DC', '#F27700']

    plt.bar(x, values, color=colors, width=0.6)
    plt.gca().set_facecolor('#E4E4E4')
    for i, v in enumerate(values):
        plt.text(x[i], v + 3.5, int(values[i]),  # 좌표 (x축 = v, y축 = y[0]..y[1], 표시 = y[0]..y[1])
                 fontsize=16,
                 fontproperties=fontprop_bold,
                 color='black',
                 horizontalalignment='center',  # horizontalalignment (left, center, right)
                 verticalalignment='center')  # verticalalignment (top, center, bottom)
    plt.axhspan(16, 84.2, color='#E6F7FF', zorder=0)
    plt.axhspan(100, 110, color='w', zorder=0)
    plt.axhline(16, zorder=0, linestyle='--', linewidth=0.8, color='#949595')
    plt.axhline(84.2, zorder=0, linestyle='--', linewidth=0.8, color='#949595')
    plt.gca().axes.yaxis.set_ticks([])
    for label in ax.get_xticklabels():
        label.set_fontproperties(fontprop_bold)
    plt.tick_params(labelsize=15, length=7, bottom=False)
    plt.ylim(0, 110)
    plt.savefig(os.path.join(RESULT_DIR, 'brain_activity.png'), dpi=300)

def plot_brain_intelligence(apf_freq:float, apf_psd:float, RESULT_DIR:str):
    '''
    plot brain intelligence
    Args:
        apf_freq (float) : IAPF frequency value
        apf_psd (float) : Percentage of subjects' apf_psd compared to normaltive data
        RESULT_DIR (str) : RESULT_DIR
    '''

    fig = go.Figure()
    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "apf_base.png")), 'xref': "x", 'yref': "y", 'x': -1, 'y': 7.4,
         'sizex': 8, 'sizey': 8,
         'sizing': "stretch", 'layer': "below"})

    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "apf_point.png")), 'xref': "x", 'yref': "y", 'x':  (apf_freq -8) * 6.64/4 -0.24 , 'y': (apf_psd) * 6.76/100 +.25,
         'sizex': .5, 'sizey': .5,
         'sizing': "stretch", 'layer': "below"})

    fig.update_layout(
        xaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        yaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        autosize=False,
        showlegend=False,
        plot_bgcolor='white', width=1200, height=1200)

    fig.update_layout(xaxis=dict(range=[-1, 10]), yaxis=dict(range=[-1, 10]))
    fig.write_image(os.path.join(RESULT_DIR, 'brain_intelligence.png'))

def plot_brain_flexibility(ratio_com:float, RESULT_DIR:str, reportLanguage: str="kr"):
    '''
    plot brain flexibility
    Args:
        ratio_com (float) : Percentage of subjects' complexity compared to normaltive data
        RESULT_DIR (str) : RESULT_DIR
        en (bool)
    '''
    start_x = 0
    if reportLanguage =="en":
        start_x = -0.15
    fig = go.Figure()
    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "complexity_base.png")), 'xref': "x", 'yref': "y", 'x': start_x, 'y': 2,
         'sizex': 71*0.15, 'sizey': 14*0.15,
         'sizing': "contain", 'layer': "below"})

    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "base_point.png")), 'xref': "x", 'yref': "y",
         'x': 0.04 + (5.17-0.04)/100 * ratio_com, 'y': 3,
         'sizex': 3.4*0.13, 'sizey': 5.6*0.13,
         'sizing': "contain", 'layer': "below"})

    fig.update_layout(
        xaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        yaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        autosize=False,
        showlegend=False,
        plot_bgcolor='white', width=1200, height=550)

    fig.update_layout(xaxis=dict(range=[-1, 6.5]), yaxis=dict(range=[-1, 4]))
    fig.write_image(os.path.join(RESULT_DIR, 'brain_flexibility.png'))


def plot_brain_balance(ratio_fas: float, RESULT_DIR: str, reportLanguage: str="kr"):
    '''
    plot brain balance
    Args:
        ratio_fas (float) : Percentage of subjects' FAA
        RESULT_DIR (str) : RESULT_DIR
    '''
    fig = go.Figure()

    start_x = 0
    start_y = 3
    if reportLanguage =="en":
        start_x = -.08
        start_y = 3
    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "faa_base.png")), 'xref': "x", 'yref': "y", 'x': start_x, 'y': start_y,
         'sizex': 7, 'sizey': 7,
         'sizing': "contain", 'layer': "below"})

    fig.update_layout(
        xaxis={'showgrid': False, 'zeroline': False, 'showline': True, 'showticklabels': False},
        yaxis={'showgrid': False, 'zeroline': False, 'showline': True, 'showticklabels': False},
        autosize=True,
        showlegend=False,
        plot_bgcolor='white', width=1200, height=700)

    theta = 180 - (ratio_fas * (9 / 5))
    a = 2 * 0.95
    b = 3 * 0.95
    x_head = a * np.cos(np.radians(theta))
    y_head = b * np.sin(np.radians(theta))

    fig.add_trace(
        go.Scatter(mode='lines', x=[3.06, x_head + 3.06], y=[-1.9, y_head - 2], line=dict(color='black', width=5)))

    fig.add_trace(
        go.Scatter(mode='markers', x=[x_head + 3.06], y=[y_head - 2],
                   marker={'line_color': 'black', 'line_width': 0, 'color': 'black', 'size': 4}))

    fig.update_layout(xaxis=dict(range=[-2, 7]), yaxis=dict(range=[-4, 4]))
    fig.write_image(os.path.join(RESULT_DIR, 'brain_balance.png'))

def plot_ans_activity(values:list, RESULT_DIR:str):
    '''
    plot ans acitivity bar plot
    Args:
        values (list) : ['TP', 'VLF', 'LF', 'HF'], percent format
        RESULT_DIR (str) : RESULT_DIR
    '''
    plt.figure(figsize=(5, 4.5))
    ax = plt.gca()
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['top'].set_visible(False)

    x = ['TP', 'VLF', 'LF', 'HF']
    color = ['#0084E1', '#FFC200', '#F94C56', '#00BD53']
    plt.bar(x, values, color=color, width=0.45)
    plt.gca().set_facecolor('#E4E4E4')

    for i, v in enumerate(values):
        plt.text(x[i], v + 5, int(values[i]),  # 좌표 (x축 = v, y축 = y[0]..y[1], 표시 = y[0]..y[1])
                 fontsize=16,
                 fontproperties = fontprop_bold,
                 color='black',
                 horizontalalignment='center',  # horizontalalignment (left, center, right)
                 verticalalignment='center')  # verticalalignment (top, center, bottom)

    plt.axhspan(16, 84.2, color='#E6F7FF',  zorder=0)
    plt.axhspan(100, 110, color='w',  zorder=0)
    plt.axhline(16, zorder=0, linestyle='--', linewidth=0.8, color='#949595')
    plt.axhline(84.2, zorder=0, linestyle='--', linewidth=0.8, color='#949595')
    plt.gca().axes.yaxis.set_ticks([])
    for label in ax.get_xticklabels():
        label.set_fontproperties(fontprop_semibold)
    plt.tick_params(labelsize=15, length=7, bottom=False)
    plt.ylim(0, 110)
    plt.savefig(os.path.join(RESULT_DIR, 'ANS_activity.png'), dpi=300)

def plot_ans_balance(values: list, RESULT_DIR: str):
    '''
    plot ans balance bar plot
    Args:
        values (list) : [SNS, PNS]
        RESULT_DIR (str) : RESULT_DIR
    '''
    fig, axes = plt.subplots(nrows=2, ncols=1, sharex=True, figsize=(7, 3.5))
    colors = ['#F30077', '#1194C8']
    grp = [0, 0]
    label = ['SNS', 'PNS']
    vline = np.linspace(10, 100, 10)
    for i, ax in enumerate(axes):
        height = .55
        ax.barh(grp[i], values[i], color=colors[i], alpha=1, height=height)
        ax.barh(grp[i], 100, color='#E4E4E4', alpha=1,height=height, zorder=0)
        ax.set_ylabel(label[i], fontsize=23, fontproperties=fontprop_semibold, rotation='horizontal', labelpad=28, ha='center', va='center')
        for v in vline:
            ax.axvline(v, color='white', linewidth=2)
        ax.text(105, -.11, str(round(values[i], 1)), fontsize=28, fontproperties=fontprop_bold, color=colors[i])
        ax.set_xticks([])
        ax.set_yticks([])
        ax.spines['bottom'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.spines['top'].set_visible(False)
        ax.set_ylim(-.5, .5)
        ax.set_xlim(0, 130)
    plt.savefig(os.path.join(RESULT_DIR, 'ANS_balance.png'), dpi=300)

def plot_stress_index(ratio_stress:float, RESULT_DIR:str, reportLanguage: str="kr"):
    '''
    plot stree inedex
    Args:
        ratio_stress (float) : Percentage of subjects' stress index compared to normaltive data
        RESULT_DIR (str) : RESULT_DIR
    '''
    fig = go.Figure()
    position_x = 0.2 + (5.22-0.2)/100 * ratio_stress
    if reportLanguage =="en":
        position_x = 0.22 + (5.13-0.22)/100 * ratio_stress
    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "si_base.png")), 'xref': "x", 'yref': "y", 'x': 0, 'y': 2,
         'sizex': 73*0.15, 'sizey': 6*0.15,
         'sizing': "contain", 'layer': "below"})

    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "base_point.png")), 'xref': "x", 'yref': "y", 'x': position_x, 'y': 3,
         'sizex': 3.4*0.13 , 'sizey': 5.5*0.13,
         'sizing': "contain", 'layer': "below"})

    fig.update_layout(
        xaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        yaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        autosize=False,
        showlegend=False,
        plot_bgcolor='white', width=1200, height=550)

    fig.update_layout(xaxis=dict(range=[-1, 6.5]), yaxis=dict(range=[-1, 4]))
    fig.write_image(os.path.join(RESULT_DIR, 'stress_index.png'))

def plot_stress_resistance(ratio_stress_resistance:float, RESULT_DIR:str, reportLanguage: str="kr"):
    '''
    plot stree inedex
    Args:
        ratio_stress_resistance (float) : Percentage of subjects' stress resistance compared to normaltive data
        RESULT_DIR (str) : RESULT_DIR
    '''
    fig = go.Figure()
    position_x = 0.2 + (5.22-0.2)/100 * ratio_stress_resistance
    if reportLanguage =="en":
        position_x = 0.22 + (5.13-0.22)/100 * ratio_stress_resistance
    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "sr_base.png")), 'xref': "x", 'yref': "y", 'x': 0, 'y': 2,
         'sizex': 73*0.15, 'sizey': 6*0.15,
         'sizing': "contain", 'layer': "below"})
    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "base_point.png")), 'xref': "x", 'yref': "y", 'x': position_x, 'y': 3,
         'sizex': 3.4*0.13 , 'sizey': 5.5*0.13,
         'sizing': "contain", 'layer': "below"})

    fig.update_layout(
        xaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        yaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        autosize=False,
        showlegend=False,
        plot_bgcolor='white', width=1200, height=550)

    fig.update_layout(xaxis=dict(range=[-1, 6.5]), yaxis=dict(range=[-1, 4]))
    fig.write_image(os.path.join(RESULT_DIR, 'stress_resistance.png'))

def plot_pse_14(x_val:float, sort:str, RESULT_DIR:str):
    '''
    plot pse depress bar
    Args:
        x_val (float) : x value
        sort (str) : category value, 'depress' or 'unrest'
        RESULT_DIR (str) : RESULT_DIR

    '''
    fig = go.Figure()

    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "pse_base_14.png")), 'xref': "x", 'yref': "y", 'x': 0.1, 'y': 2,
         'sizex': 71*0.15, 'sizey': 6*0.15,
         'sizing': "contain", 'layer': "below"})

    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "base_point.png")), 'xref': "x", 'yref': "y", 'x': x_val, 'y': 3, #0 ~4.9  0, 0.95, 1.9, 2.95, 3.9, 4.9
         'sizex': 3.4*0.13 , 'sizey': 5.5*0.13,
         'sizing': "contain", 'layer': "below"})

    fig.update_layout(
        xaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        yaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        autosize=False,
        showlegend=False,
        plot_bgcolor='white', width=1200, height=550)

    fig.update_layout(xaxis=dict(range=[-1, 6.5]), yaxis=dict(range=[-1, 4]))
    fig.write_image(os.path.join(RESULT_DIR, "pse_"+sort+".png"))

def plot_pse(x_val:float, sort:str, RESULT_DIR:str):
    '''
    plot pse depress bar
    Args:
        x_val (float) : x value
        sort (str) : category value, 'depress' or 'unrest'
        RESULT_DIR (str) : RESULT_DIR

    '''
    fig = go.Figure()

    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "pse_base.png")), 'xref': "x", 'yref': "y", 'x': 0.1, 'y': 2,
         'sizex': 71*0.15, 'sizey': 6*0.15,
         'sizing': "contain", 'layer': "below"})

    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "base_point.png")), 'xref': "x", 'yref': "y", 'x': x_val, 'y': 3, #0 ~4.9  0, 0.95, 1.9, 2.95, 3.9, 4.9
         'sizex': 3.4*0.13 , 'sizey': 5.5*0.13,
         'sizing': "contain", 'layer': "below"})

    fig.update_layout(
        xaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        yaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        autosize=False,
        showlegend=False,
        plot_bgcolor='white', width=1200, height=550)

    fig.update_layout(xaxis=dict(range=[-1, 6.5]), yaxis=dict(range=[-1, 4]))
    fig.write_image(os.path.join(RESULT_DIR, "pse_"+sort+".png"))

def plot_self_understanding(self_u:float, RESULT_DIR:str):
    '''
    Args
        self_u (str) : self understanding ratio
        RESULT_DIR (str) : RESULT_DIR
    '''
    fig = go.Figure()
    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "self_understanding_base.png")), 'xref': "x", 'yref': "y", 'x': 0, 'y': 2,
         'sizex': 73*0.15, 'sizey': 6*0.15,
         'sizing': "contain", 'layer': "below"})

    fig.add_layout_image(
        {'source': Image.open(os.path.join(BASE_DIR, "base_point.png")), 'xref': "x", 'yref': "y", 'x': self_u / 100 * 5 + 0.2, 'y': 3, #0.2  5.2
         'sizex': 3.4*0.13, 'sizey': 5.5*0.13,
         'sizing': "contain", 'layer': "below"})

    fig.update_layout(
        xaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        yaxis={'showgrid': False, 'zeroline': False, 'showline': False, 'showticklabels': False},
        autosize=False,
        showlegend=False,
        plot_bgcolor='white', width=1200, height=550)

    fig.update_layout(xaxis=dict(range=[-1, 6.5]), yaxis=dict(range=[-1, 4]))
    fig.write_image(os.path.join(RESULT_DIR, "self_understanding.png"))

def plot_statistic_mean(values, sort: str, RESULT_DIR: str, reportLanguage: str="kr"):
    '''
    plot statistic mean bar
    Args:
        values : ['전체 평균', '내 연령평균', '내 성별평균', '내 점수']
        sort (str) : category value, 'eeg' or 'ppg'
        RESULT_DIR (str) : RESULT_DIR
        en (bool)
    '''

    colors = [(0.0, 0.5176470588235295, 0.8823529411764706, .35), (0.0, 0.5176470588235295, 0.8823529411764706, .35),
              (0.0, 0.5176470588235295, 0.8823529411764706, .35)]
    temp = [0, 1, 2, 3]
    label = ['전체 평균', '내 연령평균', '내 성별평균', '내 점수']
    start_y = -17
    if reportLanguage =="en":
        label = ['All Avg', 'My age Avg', 'My Gender Avg', 'My Score']
        start_y = -19.5
    vline = np.linspace(0, 100, 11)

    if values[-1] >= 80:  # 건강
        colors.insert(3, (0.0, 0.5176470588235295, 0.8823529411764706, 1))
    elif (values[-1] >= 70) and (values[-1] < 80):  # 보통
        colors.insert(3, (0.0, 0.7411764705882353, 0.3254901960784314, 1))
    elif (values[-1] >= 60) and (values[-1] < 70):  # 경고
        colors.insert(3, (0.9490196078431372, 0.4666666666666667, 0.0, 1))
    elif values[-1] < 60:  # 위험
        colors.insert(3, (0.9764705882352941, 0.2980392156862745, 0.33725490196078434, 1))

    plt.figure(figsize=(9.1, 3.1))
    plt.barh(temp, values, color=colors, height=.4)

    for v in vline:  # vline
        plt.axvline(v, color='white', linewidth=1)
    for i, v in enumerate(values):  # value text
        if i == 3:
            plt.text(v + 3, temp[i] - 0.12, str(round(v, 1)), fontsize=16.5, fontproperties=fontprop_bold, color=colors[i])
        else:
            plt.text(v + 3, temp[i] - 0.11, str(round(v, 1)), fontsize=14, fontproperties=fontprop_semibold, color='#717171')
    for i, yi in enumerate(np.arange(len(values))):  # ytick text
        if i == 3:
            plt.gca().text(start_y, yi, label[i], horizontalalignment='left', verticalalignment='center', fontsize=12,
                           fontproperties=fontprop_bold, color=colors[i])
        else:
            plt.gca().text(start_y, yi + .01, label[i], horizontalalignment='left', verticalalignment='center', fontsize=12,
                           fontproperties=fontprop_semibold, color='#717171')

    plt.xticks([])
    plt.yticks([])
    plt.gca().yaxis.set_ticks_position('none')  # tick position 없음
    plt.gca().spines['left'].set_linewidth(1)  # 테두리 설정
    plt.gca().spines['bottom'].set_visible(False)
    plt.gca().spines['right'].set_visible(False)
    plt.gca().spines['top'].set_visible(False)
    plt.ylim(-.7, 3.7)
    plt.xlim(0, 110)
    plt.tight_layout()
    plt.savefig(os.path.join(RESULT_DIR, sort + '_mean.png'), dpi=300)


def plot_norm(sort: str, zscore: float, age: str, RESULT_DIR: str, reportLanguage: str="kr"):
    '''
    plot norm
    Args:
        sort (str) : category value, 'eeg' or 'ppg'
        zscore (float) : zscore of subjects' sort score compared to normaltive data
        age (str) : subject's age format like '20세'
    '''
    age = directory.age_modify(age, png=True)

    plt.figure(figsize=(11.7 * 1.4, 4.1 * 1.4))
    percent = round(st.norm.cdf(zscore), 3) - 0.5
    x = np.arange(-3, 3.01, 0.01)
    y = st.norm.pdf(x, 0, 1.1)
    plt.plot(x, y, linewidth=4, color='#0053CC', alpha=1)  # 테두리
    polygon = plt.fill_between(x, -0.04, y, alpha=.12, color='#0084E1', lw=0)  # 안쪽

    plt.gca().spines['bottom'].set_visible(False)
    plt.gca().spines['left'].set_visible(False)
    plt.gca().spines['right'].set_visible(False)
    plt.gca().spines['top'].set_visible(False)

    plt.xlim(-4, 3.2)
    plt.ylim(-0.15, 0.5)
    plt.gca().axes.xaxis.set_visible(False)
    plt.gca().axes.yaxis.set_visible(False)

    plt.vlines(percent * 6, -0.06, st.norm.pdf(percent * 6, 0, 1.1) - 0.02, linestyle="-", lw=2, color='#AAAAAB')

    position = '내 위치'
    low = "낮음"
    high = "높음"
    position_x = percent * 6 - 0.2
    if reportLanguage =="en":
        position = 'My position'
        low = 'Low'
        high = 'High'
        position_x = percent * 6 - 0.38

    plt.text(position_x, st.norm.pdf(percent * 6, 0, 1.1) + 0.12, position, fontproperties=fontprop_bold, fontsize=20,
             color='#0084E1')
    plt.text(percent * 6 - 0.005, st.norm.pdf(percent * 6, 0, 1.1) + 0.06, '\uf3c5', fontproperties=fontprop_awesome, size=35,
             va='center', ha='center', clip_on=True, c='#0084E1')

    a = str(round(100 - st.norm.cdf(zscore) * 100)) + "%"
    plt.text(percent * 6 - 0.14, -0.12, a, fontproperties=fontprop_bold, fontsize=25, color='#0084E1')
    plt.text(-3.35, -0.02, low, fontproperties=fontprop_semibold, fontsize=15, color='#717171')
    plt.text(3.15, -0.02, high, fontproperties=fontprop_semibold, fontsize=15, color='#717171')
    plt.savefig(os.path.join(RESULT_DIR, sort + '_norm.png'), dpi=300)


def plot_4class( scores: dict, sort: str, RESULT_DIR: str):
    '''
    plot brain acitivity bar plot
    Args:
        score (int) : Maumgyeol Score
        sort (str) : eeg or ppg
        RESULT_DIR (str) : RESULT_DIR
    '''

    items = list(scores.items())
    max_score = max(scores.values())

    for idx, (label, score) in enumerate(items):

        fig, ax = plt.subplots(figsize=(6, 6))
        ax = plt.subplot(projection='polar')

        # convert score (0–100) to radians
        xs = (score * 2 * pi) / 100
        left = (90 * 2 * pi) / 360

        bar_color = '#0053CC'  # 기본 파란색

        if score == max_score:
            if idx == 0:
                bar_color = '#6FAE3C'  #연두
            else:
                bar_color = '#E67E22'  #주황

        #colors = ['#121CA7', '#0053CC']
        ys = [1, 1]



        # score bar

        bar = ax.barh(
            ys[1], xs, left=left, height=1.4,
            color=bar_color, zorder=2)

        # bars는 BarContainer, 내부 Rectangle patch들에 직접 스타일 적용
        for p in bar.patches:
            p.set_edgecolor("white")  # 배경색(흰색)과 동일하게
            p.set_linewidth(5)

        ax.barh(ys[0], 2 * pi, left=left, height=1.1,
                color='#a2a9b0', alpha=0.2)


        # text
        plt.ylim(-4, 4)

        plt.text((10 * pi * 2) / 100, -4, f"{score}%",
                     ha='center', va='center',
                     fontsize=45, fontproperties=fontprop_semibold)


        # clean
        plt.xticks([])
        plt.yticks([])
        ax.spines.clear()

        # save
        save_path = os.path.join(
            RESULT_DIR, f"{sort}_{label}_score.png"
        )
        plt.savefig(save_path, dpi=300, bbox_inches='tight')
        plt.close()


def plot_mdd_score(score: float, sort: str, RESULT_DIR: str, colors=('#AAD2E6', "#191796"), reportLanguage: str = "kr"):
    '''
    우울증/정상 확률 도넛(원형 게이지) 플롯. plot_4class 와 동일한 각진(흰 테두리)
    스타일이며 색상만 파라미터로 받는다 (우울증=파랑 계열, 정상=초록 계열).
    Args:
        score (float) : 0~100 확률(%)
        sort (str) : 저장 파일명 접두어 (예: 'mdd_dep', 'mdd_normal')
        RESULT_DIR (str) : RESULT_DIR
        colors (tuple) : (사용 안 함/호환용, 진행 바 색상) - colors[1]이 실제 바 색상
    '''
    bar_color = colors[1]

    fig, ax = plt.subplots(figsize=(6, 6))
    ax = plt.subplot(projection='polar')

    xs = (score * 2 * pi) / 100
    left = (90 * 2 * pi) / 360
    ys = [1, 1]

    bar = ax.barh(ys[1], xs, left=left, height=1.4, color=bar_color, zorder=2)
    for p in bar.patches:
        p.set_edgecolor("white")   # 각진 바 사이 흰 테두리 - plot_4class 와 동일
        p.set_linewidth(5)

    ax.barh(ys[0], 2 * pi, left=left, height=1.1, color='#a2a9b0', alpha=0.2)

    plt.ylim(-4, 4)
    score_text = f"{score:.1f}%"
    plt.text((10 * pi * 2) / 100, -4, score_text, ha='center', va='center',
             fontsize=45, fontproperties=fontprop_semibold, color='black')

    plt.xticks([])
    plt.yticks([])
    ax.spines.clear()
    plt.savefig(os.path.join(RESULT_DIR, sort + '_score.png'), dpi=300, bbox_inches='tight')  # plot_4class 와 동일
    plt.close()
