import os from flask import Flask, session from flask_pymongo import PyMongo from dotenv import load_dotenv load_dotenv() app = Flask(__name__) app.config["MONGO_URI"] = os.environ.get("MONGO_URI") if app.config["MONGO_URI"] and "mongodb.net/?" in app.config["MONGO_URI"]: app.config['MONGO_URI'] = app.config['MONGO_URI'].replace("mongodb.net/?", "mongodb.net/swiftquery?") mongo = PyMongo(app) def debug_task(): with app.app_context(): # Simulate session user_id. We don't know it exactly, but let's try 1 as it's common or implied by the error 'KeyError: 1' if it was a lookup # Or maybe the error is looking up key 1 in a dict. # Let's search for any chat sessions print("Finding chat sessions...") all_chats = list(mongo.db.chatsession.find()) print(f"Found {len(all_chats)} chats.") for chat in all_chats: print(f"Processing chat: {chat.get('id')} / {chat.get('sql_id')}") # This is the logic we added if chat.get('doctor_id'): d_id = chat['doctor_id'] print(f" Doctor ID: {d_id} (Type: {type(d_id)})") # Check find_one try: query = {"$or": [{"sql_id": d_id}, {"id": d_id}]} print(f" Query: {query}") doc = mongo.db.doctor.find_one(query) print(f" Found Doc: {doc.get('name') if doc else 'None'}") if doc: print(f" Doc Name: {doc['name']}") chat['doctor_name'] = doc['name'] if doc else "Unknown" except Exception as e: print(f" ERROR processing chat {chat.get('id')}: {e}") import traceback traceback.print_exc() else: chat['doctor_name'] = "AI Assistant" print(" Success.") if __name__ == "__main__": debug_task()