from fastapi import APIRouter, HTTPException
from typing import Dict, List
import json

from app.schemas.human_os_schema import StartHumanOSRequest, AnswerHumanOSRequest
from app.services import human_os_questions, human_os_scoring
from app.models import human_os_module
from app.core.config import logger

router = APIRouter(
    prefix="/goalskill-sales/api/human_os",
    tags=["HumanOS"]
)

@router.post("/start")
async def start_human_os(request: StartHumanOSRequest):
    try:
        # 進行状態初期化
        human_os_module.clear_session_logs(request.session_id)
        
        all_questions = human_os_questions.get_all_questions()
        if not all_questions:
            raise HTTPException(status_code=500, detail="No questions available")
        
        # 最初の問題を返却
        first_question = all_questions[0]
        
        return {
            "question_id": first_question["id"],
            "question_type": first_question["type"],
            "question_text": first_question["text"],
            "options": first_question["options"],
            "current": 1,
            "total": len(all_questions)
        }
    except Exception as e:
        logger.error(f"HumanOS Start Error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/answer")
async def answer_human_os(request: AnswerHumanOSRequest):
    try:
        # 数字のみを抽出
        option_val = request.selected_option
        if ":" in option_val:
            option_val = option_val.split(":")[0].strip()

        # 回答保存 → human_os_log
        human_os_module.save_answer(
            session_id=request.session_id,
            question_id=request.question_id,
            selected_option=option_val,
            value=request.value
        )
        
        answered_count = human_os_module.get_answer_count(request.session_id)
        all_questions = human_os_questions.get_all_questions()
        total_questions = len(all_questions)
        
        # 全問完了時 → スコア計算 → human_os_Output + user_profile_summary に保存
        if answered_count >= total_questions:
            # 1. DB에서 전체 답변 가져오기
            answers = human_os_module.get_all_answers(request.session_id)
            
            # 2. scoring으로 축별 Node 레벨 + 総合スコア 계산 (역채점 포함)
            axis_result, overall_score = human_os_scoring.calculate_human_os(answers)
            
            # 3. 일본어 키로 변환
            db_result = human_os_scoring.format_for_db(axis_result)
            
            # 4. JSON 문자열로 변환 후 DB 저장 (総合スコア는 output_value 컬럼에)
            node_score_json = json.dumps(db_result, ensure_ascii=False)
            human_os_module.save_or_update_output(request.session_id, node_score_json, overall_score)
            
            return {
                "status": "completed",
                "result": {
                    "summary": "HumanOS診断が完了しました。",
                    "scores": db_result
                }
            }
        
        # 次の問題を返却
        next_question = all_questions[answered_count]
        return {
            "status": "continue",
            "next_question": {
                "question_id": next_question["id"],
                "question_type": next_question["type"],
                "question_text": next_question["text"],
                "options": next_question["options"],
                "current": answered_count + 1,
                "total": len(all_questions)
            }
        }
        
    except Exception as e:
        logger.error(f"HumanOS Answer Error: {e}")
        raise HTTPException(status_code=500, detail=str(e))
