# 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