import os
from flask import Flask, request, jsonify, send_from_directory
from openai import OpenAI
from dotenv import load_dotenv

load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

app = Flask(__name__)  # 정적 파일은 ./static 폴더에서 자동 서빙 (/static/...)


@app.route("/")
def index():
    # static/chatbot.html 을 첫 페이지로 서빙
    return send_from_directory(app.static_folder, "chatbot.html")


@app.route("/api/chat", methods=["POST"])
def chat():
    message = request.json["message"]
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "당신은 친절한 AI 도우미입니다."},
            {"role": "user", "content": message},
        ],
    )
    return jsonify({"answer": response.choices[0].message.content})


if __name__ == "__main__":
    app.run(debug=True, port=5000)
