import os
from flask import Flask, request, jsonify
from flask_cors import CORS

from src.rag.gemeni import GeminiClient
from src.mongo import get_database

app = Flask(__name__)
CORS(app)  

try:
    brain = GeminiClient()
    db = get_database()
    print("--- Backend Components Initialized Successfully ---")
except Exception as e:
    print(f"CRITICAL ERROR during initialization: {e}")

@app.route('/')
def health_check():
    return {
        "status": "online",
        "message": "The Waiter is ready at the counter!"
    }

@app.route('/chat', methods=['POST'])
def chat():
    data = request.json
    user_query = data.get("message")

    if not user_query:
        return jsonify({"error": "You didn't say anything!"}), 400

    try:
        context = ""
        ai_reply = brain.ask(user_query, context)
        return jsonify({
            "status": "success",
            "reply": ai_reply
        })
    except Exception as e:
        return jsonify({
            "status": "error",
            "message": str(e)
        }), 500

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