# back/app/routers/mbti_router.py

from fastapi import APIRouter
from fastapi.responses import JSONResponse
from app.services.goalskill_classifier import classify_and_save
import json

# 모듈 임포트
from app.services import mbti_questions, mbti_scoring
from app.services.mbti_descriptions import get_mbti_description
from app.services.mbti_tips import get_mbti_tips
from app.schemas.mbti import MbtiLogRequest, MbtiCalcRequest
from app.models import mbti_module 

router = APIRouter(
    prefix="",
    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")
async 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)
        mbti_tips = get_mbti_tips(mbti_type)

        # 2) データ加工 (MBTI軸パーセンテージに変換して保存)
        system_msg = "[SYSTEM] Diagnosis Completed."
        mbti_scores = mbti_scoring.convert_to_mbti_scores(scores)
        scores_json = json.dumps(mbti_scores)

        # 3) DB 저장
        mbti_module.save_mbti_result_transaction(
            req.session_id, 
            system_msg, 
            mbti_type, 
            scores_json,
            mbti_description
        )
        result_text = f"MBTI TYPE: {mbti_type} - {mbti_description}"

        await classify_and_save(
            session_id = req.session_id,
            sender = "I",
            part = "A",
            text = result_text
        )
        
        return {
            "status": "success",
            "mbti_type": mbti_type,
            "mbti_description": mbti_description,
            "mbti_tips": mbti_tips,
            "mbti_scores": mbti_scores,
            "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")
async 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)
        mbti_tips = get_mbti_tips(mbti_type)
        
        # DB 저장 (직접 입력 타입에서 축 방향을 역산하여 scores 생성)
        system_msg = "[SYSTEM] Direct MBTI Type Input."
        # 예: ISTP-A → EI:I, SN:S, TF:T, JP:P 각 100%
        core_type = mbti_type.split("-")[0]  # "ISTP"
        direct_scores = {
            "EI": {"E": 0.0, "I": 100.0} if core_type[0] == "I" else {"E": 100.0, "I": 0.0},
            "SN": {"S": 100.0, "N": 0.0} if core_type[1] == "S" else {"S": 0.0, "N": 100.0},
            "TF": {"T": 100.0, "F": 0.0} if core_type[2] == "T" else {"T": 0.0, "F": 100.0},
            "JP": {"J": 100.0, "P": 0.0} if core_type[3] == "J" else {"J": 0.0, "P": 100.0},
        }
        scores_json = json.dumps(direct_scores)
        
        mbti_module.save_mbti_result_transaction(
            session_id, 
            system_msg, 
            mbti_type, 
            scores_json,
            mbti_description
        )
        result_text = f"MBTI TYPE: {mbti_type} - {mbti_description}"

        await classify_and_save(
            session_id = session_id,
            sender = "I",
            part = "A",
            text = result_text
        )
        
        return {
            "status": "success",
            "mbti_type": mbti_type,
            "mbti_description": mbti_description,
            "mbti_tips": mbti_tips,
            "mbti_scores": direct_scores
        }
        
    except Exception as e:
        return JSONResponse(status_code=500, content={"status": "error", "message": str(e)})

# 4. 결과 조회 API
@router.get("/result/{session_id}")
async def get_mbti_result(session_id: str):
    """기존 MBTI 결과를 리턴"""
    output = mbti_module.get_output(session_id)
    if not output:
        return JSONResponse(status_code=404, content={"status": "error", "message": "Result not found"})
    
    mbti_type = output.get("result", "")
    mbti_description = output.get("description", "")
    scores_json = output.get("scores", "{}")
    import json
    try:
        mbti_scores = json.loads(scores_json)
    except:
        mbti_scores = {}
        
    mbti_tips = get_mbti_tips(mbti_type)
    
    return {
        "status": "success",
        "result": {
            "mbti_type": mbti_type,
            "mbti_description": mbti_description,
            "mbti_tips": mbti_tips,
            "mbti_scores": mbti_scores
        }
    }