# app/services/mbti_scoring.py
# mbti 점수 계산 로직

from typing import Dict, List

def calculate_scores(user_responses: Dict[str, int], questions: List[dict]) -> Dict[str, int]:
    """
    사용자의 답변과 질문 정보를 받아 각 Factor별 점수를 계산합니다.
    """
    scores = {"E": 0, "A": 0, "C": 0, "S": 0, "O": 0}
    max_scale = 5

    for q in questions:
        q_id = str(q["id"])
        factor = q["factor"]
        key = q["key"]
        
        # 사용자가 해당 문제에 답변했는지 확인 (없으면 기본값 3)
        user_score = user_responses.get(q_id, 3) 
        
        # 역방향 채점 처리 (key가 -1이면 점수 뒤집기)
        if key == 1:
            final_score = user_score
        else:
            final_score = (max_scale + 1) - user_score
            
        scores[factor] += final_score

    return scores

def convert_to_mbti(scores: Dict[str, int]) -> str:
    """
    계산된 점수(Scores)를 MBTI 4글자 유형(String)으로 변환합니다.
    """
    mbti_result = ""
    threshold = 30 

    mbti_result += "E" if scores["E"] >= threshold else "I"
    mbti_result += "N" if scores["O"] >= threshold else "S"
    mbti_result += "F" if scores["A"] >= threshold else "T"
    mbti_result += "J" if scores["C"] >= threshold else "P"
    
    # 정서안정성 (Identity: -A / -T)
    suffix = "-A" if scores["S"] >= threshold else "-T"
    
    return mbti_result + suffix


def convert_to_mbti_scores(scores: Dict[str, int]) -> Dict:
    """
    Big Fiveスコア(10~50)をMBTI 4軸パーセンテージに変換する。
    グラフ作成者がそのまま使える形式に変換。
    
    Args:
        scores: {"E": 30, "A": 30, "C": 30, "S": 30, "O": 30}
    
    Returns:
        {
            "EI": {"E": 50.0, "I": 50.0},
            "SN": {"S": 50.0, "N": 50.0},
            "TF": {"T": 50.0, "F": 50.0},
            "JP": {"J": 50.0, "P": 50.0}
        }
    """
    e_pct = round(((scores["E"] - 10) / 40) * 100, 1)
    n_pct = round(((scores["O"] - 10) / 40) * 100, 1)
    f_pct = round(((scores["A"] - 10) / 40) * 100, 1)
    j_pct = round(((scores["C"] - 10) / 40) * 100, 1)

    return {
        "EI": {"E": e_pct, "I": round(100 - e_pct, 1)},
        "SN": {"S": round(100 - n_pct, 1), "N": n_pct},
        "TF": {"T": round(100 - f_pct, 1), "F": f_pct},
        "JP": {"J": j_pct, "P": round(100 - j_pct, 1)}
    }