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

app = Flask(__name__)

# Cấu hình logging
logging.basicConfig(level=logging.DEBUG)

# Cấu hình CORS, cho phép từ domain cụ thể hoặc tất cả (thử nghiệm)
CORS(app, resources={r"/api/*": {"origins": "*"}})  # Thay "*" bằng domain PHP nếu cần

@app.route('/api/chat', methods=['POST', 'OPTIONS'])
def chat():
    # Xử lý yêu cầu OPTIONS (cho CORS preflight)
    if request.method == 'OPTIONS':
        app.logger.debug('Received OPTIONS request')
        return jsonify({}), 200

    # Xử lý yêu cầu POST
    try:
        app.logger.debug(f'Received POST request: {request.get_json()}')
        data = request.get_json()
        if not data or 'message' not in data:
            app.logger.error('No message provided in request')
            return jsonify({'error': 'No message provided'}), 400
        
        user_message = data.get('message', '')
        if not user_message:
            app.logger.error('Message cannot be empty')
            return jsonify({'error': 'Message cannot be empty'}), 400
        
        # Xử lý tin nhắn (có thể tích hợp AI)
        bot_reply = f"RAG: How can I assist you further?"
        app.logger.debug(f'Sending response: {bot_reply}')
        return jsonify({'reply': bot_reply})
    except Exception as e:
        app.logger.error(f'Server error: {str(e)}')
        return jsonify({'error': f'Server error: {str(e)}'}), 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000, debug=True)