from flask import Flask, request, jsonify
from flask_cors import CORS
import logging
import os
from dotenv import load_dotenv

# Import trực tiếp hàm từ AI Agent
from ai_agent import process_with_ai_agent

load_dotenv("venv/api.env")

app = Flask(__name__)
logging.basicConfig(level=logging.DEBUG)
CORS(app, resources={r"/api/*": {"origins": "*"}})

def process_with_ai_agent_wrapper(input_text):
    """Gọi AI Agent để xử lý input"""
    return process_with_ai_agent(input_text)

@app.route('/api/chat', methods=['POST', 'OPTIONS'])
def chat():
    if request.method == 'OPTIONS':
        return jsonify({}), 200

    try:
        data = request.get_json()
        if not data or 'message' not in data:
            return jsonify({'error': 'No message provided'}), 400

        user_message = data.get('message', '').strip()
        if not user_message:
            return jsonify({'error': 'Message cannot be empty'}), 400

        ai_response = process_with_ai_agent_wrapper(user_message)
        if ai_response is None:
            return jsonify({'error': 'AI Agent failed to process the input'}), 500

        return jsonify({'reply': ai_response})

    except Exception as e:
        logging.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)
