# 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)으로 변환합니다.
    퍼센트 환산 후 50% 기준으로 판정 (convert_to_mbti_scores와 동일 기준)
    """
    max_score = 50  # 각 Factor 최대점 (문항수 × 5)

    def to_pct(val):
        pct = (val / max_score) * 100
        return max(0.0, min(100.0, pct))

    mbti_result = ""
    mbti_result += "E" if to_pct(scores["E"]) >= 50 else "I"
    mbti_result += "N" if to_pct(scores["O"]) >= 50 else "S"
    mbti_result += "F" if to_pct(scores["A"]) >= 50 else "T"
    mbti_result += "J" if to_pct(scores["C"]) >= 50 else "P"
    
    # 정서안정성 (Identity: -A / -T)
    suffix = "-A" if to_pct(scores["S"]) >= 50 else "-T"
    
    return mbti_result + suffix


def convert_to_mbti_scores(scores: Dict[str, int]) -> dict:
    """
    Big Five 원점수를 MBTI 축 퍼센트로 변환.
    각 축의 합이 100%가 되도록 계산.
    """
    max_score = 50  # 각 Factor 최대점 (문항수 × 5)
    
    def to_pct(val):
        pct = (val / max_score) * 100
        return max(0.0, min(100.0, pct))
    
    e_pct = to_pct(scores["E"])
    a_pct = to_pct(scores["A"])
    c_pct = to_pct(scores["C"])
    s_pct = to_pct(scores["S"])
    o_pct = to_pct(scores["O"])
    
    return {
        "EI": {"E": round(e_pct, 1), "I": round(100 - e_pct, 1)},
        "SN": {"S": round(100 - o_pct, 1), "N": round(o_pct, 1)},
        "TF": {"T": round(100 - a_pct, 1), "F": round(a_pct, 1)},
        "JP": {"J": round(c_pct, 1), "P": round(100 - c_pct, 1)},
    }