from flask import Flask, request, jsonify
import google.generativeai as genai
import json
import pymysql
from datetime import datetime, time
from zoneinfo import ZoneInfo

app = Flask(__name__)

# ---------------------------
# ✅ Gemini API 키 (하드코딩)
# ---------------------------
API_KEY = 'AIzaSyDHmmzx48f4L0rBUvZYaHg3cjfmWlGVFdc'
genai.configure(api_key=API_KEY)

# ---------------------------
# ✅ MySQL 접속 설정
# ---------------------------
DB_CONFIG = {
    "host": "119.205.233.11",
    "user": "changgi",
    "password": "vkdnjgus13",
    "database": "versatile",
    "charset": "utf8mb4",
    "cursorclass": pymysql.cursors.DictCursor
}

# ---------------------------
# 글로벌 변수
# ---------------------------
system_prompt_habby = ""            # id=4
system_prompt_granceed = ""         # id=5
system_prompt_granceed_tools = ""   # id=6
system_prompt_yonex_daegu = ""      # id=7

MAX_MESSAGE_LENGTH = 100
MAX_USER_QUERIES = 30
user_query_count = {}

# ---------------------------
# 운영시간 체크
# ---------------------------
def is_allowed_now_kst() -> bool:
    now = datetime.now(ZoneInfo("Asia/Seoul"))
    wd = now.weekday()  # 월=0 ... 일=6
    t = now.time()

    if wd in (5, 6):  # 토/일은 24시간 허용
        return True

    return ((time(0, 0, 0) <= t < time(6, 0, 0)) or
            (time(18, 0, 0) <= t <= time(23, 59, 59)))

# ---------------------------
# DB에서 프롬프트 1회 로드
# ---------------------------
def load_prompt_from_db(prompt_id: int) -> str:
    try:
        conn = pymysql.connect(**DB_CONFIG)
        with conn.cursor() as cur:
            cur.execute("SELECT prompt_text FROM ai_prompt_table WHERE id=%s", (prompt_id,))
            row = cur.fetchone()
            if row and row.get("prompt_text"):
                print(f"[INFO] prompt id={prompt_id} 로드 성공")
                return row["prompt_text"]
    except Exception as e:
        print(f"[WARN] 프롬프트 로드 오류 (id={prompt_id}): {e}")
    finally:
        if 'conn' in locals():
            conn.close()

    return '{"block": true, "response": "(챗봇) 내부 오류로 응답할 수 없습니다."}'

# ---------------------------
# Webhook 엔드포인트
# ---------------------------
@app.route('/webhook/<bot_name>', methods=['POST'])
def webhook(bot_name):
    data = request.json or {}

    # ✅ 운영시간 체크
    if not is_allowed_now_kst():
        return ('', 204)

    # ✅ 프롬프트 분기
    if bot_name == 'habby':
        current_system_prompt = system_prompt_habby
    elif bot_name == 'granceed':
        current_system_prompt = system_prompt_granceed
    elif bot_name == 'granceed_tools':
        current_system_prompt = system_prompt_granceed_tools
    elif bot_name == 'yonex-daegu':
        current_system_prompt = system_prompt_yonex_daegu
    else:
        current_system_prompt = system_prompt_habby

    user_message = data.get('textContent', {}).get('text', '') or ''
    user_id = data.get('user', '') or ''
    input_type = data.get('textContent', {}).get('inputType', '') or ''

    if input_type != "typing":
        return ('', 204)

    # ✅ 질문 횟수 체크
    user_query_count[user_id] = user_query_count.get(user_id, 0) + 1
    if user_query_count[user_id] > MAX_USER_QUERIES:
        return jsonify({
            "event": "send",
            "textContent": {
                "text": "(챗봇) 질의 횟수를 초과하셨습니다. 영업시간(9시~17시)에 문의 부탁드립니다."
            }
        })

    # ✅ 메시지 길이 제한
    if len(user_message) > MAX_MESSAGE_LENGTH:
        return jsonify({
            "event": "send",
            "textContent": {
                "text": "(챗봇) 질문이 너무 길어요! 100자 이내로 짧게 다시 질문해주세요~"
            }
        })

    try:
        # 모델 초기화
        model = genai.GenerativeModel(
            model_name='gemini-1.5-flash-latest',
            system_instruction=current_system_prompt,
            generation_config={"response_mime_type": "application/json"}
        )

        completion = model.generate_content(user_message)
        reply_json = completion.text.strip()

        reply_dict = json.loads(reply_json)
        if reply_dict.get('block'):
            reply_text = "(챗봇) 현재는 배송 및 매장 안내 외 다른 상담은 불가합니다. 다른 상담은 영업시간(오전 9시~오후 5시)에 문의해주세요."
        else:
            reply_text = reply_dict.get('response', "(챗봇) 죄송합니다. 답변 생성 오류입니다.")

    except Exception as e:
        print(f"[오류] Gemini API 호출 오류: {e}")
        reply_text = "(챗봇) 죄송합니다. 시스템 오류가 발생했습니다. 잠시 후 다시 시도해주세요."

    return jsonify({
        "event": "send",
        "textContent": {"text": reply_text}
    })

# ---------------------------
# 앱 시작 시 프롬프트 캐싱
# ---------------------------
if __name__ == '__main__':
    system_prompt_habby = load_prompt_from_db(4)            # id=4
    system_prompt_granceed = load_prompt_from_db(5)         # id=5
    system_prompt_granceed_tools = load_prompt_from_db(6)   # id=6
    system_prompt_yonex_daegu = load_prompt_from_db(7)      # id=7
    app.run(host='0.0.0.0', port=5000)
