from typing import List, Dict
import mysql.connector
from app.core import get_db_connection, logger

# Chat 전용 DB 모듈
# 1. 로그 저장 함수
def save_chat_log(session_id, mode, sender, message):
    try:
        conn = get_db_connection()
        cursor = conn.cursor()
        sql = "INSERT INTO chat_history (session_id, sender, message) VALUES (%s, %s, %s)"
        cursor.execute(sql, (session_id, sender, message))
        conn.commit()
        cursor.close()
        conn.close()
    except Exception as e:
        logger.error(f"Chat DB Save Error: {e}")

# 2. 히스토리 조회 함수
def get_history_from_db(session_id, mode):
    try:
        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        sql = "SELECT sender, message FROM chat_history WHERE session_id = %s ORDER BY id ASC"
        cursor.execute(sql, (session_id,))
        rows = cursor.fetchall()
        cursor.close()
        conn.close()
        return rows
    except Exception as e:
        logger.error(f"Chat DB Load Error: {e}")
        return []
