# 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.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)

        # 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,
            "scores": scores
        }

    except Exception as e:
        print(f"[MBTI Calc Error] {e}")
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})