import os
import sys
import traceback
import threading
from flask import Flask, request, jsonify
from dotenv import load_dotenv
import agent

# Load environment variables
basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, '.env'))

app = Flask(__name__)

# We will store the last error here so you can see it on the website
LAST_ERROR = "No errors! The bot is waiting for a message."

def run_agent_safely(chat_id, text):
    global LAST_ERROR
    try:
        import asyncio
        # Create a fresh, isolated environment for the AI to think
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(agent._chat_with_agent(chat_id, text))
        loop.close()
    except Exception as e:
        # If it crashes, save the exact error message!
        LAST_ERROR = traceback.format_exc()

@app.route('/', methods=['GET'])
def index():
    # Display the status and the last error on the homepage
    html = f"""
    <h1>Agent Telegram Bot is ONLINE!</h1>
    <h3>Last Bot Error:</h3>
    <pre style="background:#eee; padding:10px; border:1px solid #ccc;">{LAST_ERROR}</pre>
    <p><i>If the bot doesn't reply, refresh this page to see what went wrong.</i></p>
    """
    return html

@app.route('/webhook', methods=['POST'])
def webhook():
    global LAST_ERROR
    try:
        update = request.get_json()
        
        if not update or 'message' not in update:
            return jsonify({"status": "ignored"}), 200
            
        message = update['message']
        if 'text' not in message:
            return jsonify({"status": "ignored"}), 200
            
        chat_id = message['chat']['id']
        text = message['text']
        
        # Run the agent in an isolated thread, but wait for it to finish!
        t = threading.Thread(target=run_agent_safely, args=(chat_id, text))
        t.start()
        t.join() # Forces the server to wait for the AI!
        
    except Exception as e:
        LAST_ERROR = traceback.format_exc()
        
    return jsonify({"status": "ok"}), 200

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5000)
