"""
==============================================================================
Goalskill 라우터 - 분류 알고리즘 API 엔드포인트
==============================================================================
테스트/디버그 및 외부 파트에서도 HTTP로 호출 가능한 API.
"""

from fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from typing import Literal, Optional
from app.services.goalskill_classifier import classify_and_save, classify_only
from app.models.goalskill_module import (
    get_from_goalskill_table,
    get_all_goalskill_data,
    get_talk_count,
    VALID_TABLES,
)
from app.core.config import logger
from app.schemas.goalskill_schema import ClassifyAndSaveRequest, ClassifyOnlyRequest, TableQueryRequest

router = APIRouter(prefix="/goalskill", tags=["Goalskill Classifier"])


# ============================================================================
# API 엔드포인트
# ============================================================================

@router.post("/classify-save")
async def api_classify_and_save(request: ClassifyAndSaveRequest):
    """
    INPUT 데이터를 분류하고 Goalskill_DB에 저장.

    - sender, part는 호출 시 전달
    - H/S, T/P/R은 알고리즘이 자동 판단
    """
    try:
        result = await classify_and_save(
            session_id=request.session_id,
            sender=request.sender,
            part=request.part,
            text=request.text,
        )
        return result

    except Exception as e:
        logger.error(f"[Goalskill API] classify-save error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/classify-only")
async def api_classify_only(request: ClassifyOnlyRequest):
    """
    분류만 수행 (저장하지 않음). 디버그/테스트용.

    어떤 테이블로 분류되는지 확인할 수 있습니다.
    """
    try:
        result = classify_only(
            sender=request.sender,
            part=request.part,
            text=request.text,
        )
        return result

    except Exception as e:
        logger.error(f"[Goalskill API] classify-only error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/query")
async def api_query_table(request: TableQueryRequest):
    """
    특정 Goalskill_DB 테이블의 데이터 조회.
    """
    try:
        if request.table_name not in VALID_TABLES:
            raise HTTPException(
                status_code=400,
                detail=f"Invalid table name: {request.table_name}. "
                       f"Valid tables: {sorted(VALID_TABLES)}"
            )

        data = get_from_goalskill_table(request.table_name, request.session_id)
        return {
            "table_name": request.table_name,
            "session_id": request.session_id,
            "count": len(data),
            "data": data,
        }

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"[Goalskill API] query error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/all/{session_id}")
async def api_get_all_data(session_id: str):
    """
    유저의 모든 Goalskill_DB 데이터 조회 (48 테이블).
    데이터가 있는 테이블만 반환합니다.
    """
    try:
        data = get_all_goalskill_data(session_id)
        return {
            "session_id": session_id,
            "tables_with_data": len(data),
            "data": data,
        }

    except Exception as e:
        logger.error(f"[Goalskill API] get-all error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/talk-count/{session_id}")
async def api_get_talk_count(
    session_id: str,
    goal_scope: Optional[str] = None,
    part: Optional[str] = None
):
    """
    유저의 대화 횟수 합계 조회.

    Query params:
    - goal_scope: "H" 또는 "S" (생략 시 모두)
    - part: "A"~"D" (생략 시 모두)
    """
    try:
        count = get_talk_count(session_id, goal_scope, part)
        return {
            "session_id": session_id,
            "goal_scope": goal_scope or "ALL",
            "part": part or "ALL",
            "talk_count": count,
        }

    except Exception as e:
        logger.error(f"[Goalskill API] talk-count error: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/tables")
async def api_list_tables():
    """
    유효한 48개 테이블 목록 반환 (디버그용).
    """
    tables_by_group = {}
    for table in sorted(VALID_TABLES):
        # 그룹핑: HA_*, HB_*, SA_*, ...
        prefix = table[:2]  # "HA", "HB", "SA", ...
        if prefix not in tables_by_group:
            tables_by_group[prefix] = []
        tables_by_group[prefix].append(table)

    return {
        "total_tables": len(VALID_TABLES),
        "tables": tables_by_group,
    }
