# back/app/routers/mbti_router.py

from fastapi import APIRouter
from fastapi.responses import JSONResponse
import json

# 모듈 임포트
from app.services import mbti_questions, mbti_scoring
from app.services.mbti_descriptions import get_mbti_description
from app.schemas.mbti import MbtiLogRequest, MbtiCalcRequest
from app.models import mbti_module 

router = APIRouter(
    prefix="/goal-skill-t/api/MBTI",
    tags=["MBTI"]
)

# 1. 대화 로그 저장 API
@router.post("/log")
def log_mbti_chat(req: MbtiLogRequest):
    try:
        mbti_module.insert_chat_log(req.session_id, req.sender, req.message)
        
        return {"status": "success"}
    except Exception as e:
        print(f"[MBTI Log Error] {e}")
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})

# 2. 결과 계산 및 저장 API
@router.post("/calculate")
def calculate_mbti(req: MbtiCalcRequest):
    try:
        # 1) 비즈니스 로직 (계산)
        questions = mbti_questions.get_questions()
        scores = mbti_scoring.calculate_scores(req.answers, questions)
        mbti_type = mbti_scoring.convert_to_mbti(scores)
        
        # MBTI 설명 가져오기
        mbti_description = get_mbti_description(mbti_type)

        # 2) 데이터 가공
        system_msg = "[SYSTEM] Diagnosis Completed."
        scores_json = json.dumps(scores)

        # 3) DB 저장
        mbti_module.save_mbti_result_transaction(
            req.session_id, 
            system_msg, 
            mbti_type, 
            scores_json
        )

        return {
            "status": "success",
            "mbti_type": mbti_type,
            "mbti_description": mbti_description,
            "scores": scores
        }

    except Exception as e:
        print(f"[MBTI Calc Error] {e}")
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})

# 3. 직접 MBTI 타입 입력 API
@router.post("/direct")
def set_direct_mbti(req: dict):
    """
    사용자가 직접 MBTI 타입을 입력한 경우 처리
    """
    try:
        session_id = req.get("session_id")
        mbti_type = req.get("direct_mbti_type", "").upper().strip()
        
        if not session_id or not mbti_type:
            return JSONResponse(status_code=400, content={"status": "error", "message": "session_id and direct_mbti_type are required"})
        
        # MBTI 타입 유효성 검사 (예: ENFJ-A, INTJ-T 등)
        import re
        mbti_pattern = re.compile(r'^[EI][NS][FT][JP]-[AT]$')
        if not mbti_pattern.match(mbti_type):
            return JSONResponse(status_code=400, content={"status": "error", "message": "Invalid MBTI type format. Expected format: XXXX-A or XXXX-T"})
        
        # MBTI 설명 가져오기
        mbti_description = get_mbti_description(mbti_type)
        
        # DB 저장 (빈 scores로 저장)
        system_msg = "[SYSTEM] Direct MBTI Type Input."
        scores_json = json.dumps({})
        
        mbti_module.save_mbti_result_transaction(
            session_id, 
            system_msg, 
            mbti_type, 
            scores_json
        )
        
        return {
            "status": "success",
            "mbti_type": mbti_type,
            "mbti_description": mbti_description
        }
        
    except Exception as e:
        print(f"[MBTI Direct Error] {e}")
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})