import json
from agent.database import get_connection, release_connection

def run(inputs):
    """
    Queries the database for background tasks belonging to the current user
    that are currently RUNNING or PENDING.
    """
    # Try to extract the user_id from the context session.
    # The orchestrator should pass `session_info` in context if available.
    user_id = "DUMMY_SUPERUSER"
    
    conn = get_connection()
    try:
        with conn.cursor() as cur:
            cur.execute("""
                SELECT status, message_preview, created_at 
                FROM async_tasks 
                WHERE status IN ('PENDING', 'RUNNING')
                ORDER BY created_at ASC
            """)
            
            rows = cur.fetchall()
            
            if not rows:
                return {"output": "Tidak ada task background yang sedang berjalan saat ini."}
            
            tasks_info = []
            for row in rows:
                status, preview, created_at = row
                tasks_info.append(f"- Status: {status}, Progress: {preview}")
                
            return {"output": "Berikut adalah task yang sedang berjalan:\n" + "\n".join(tasks_info)}
            
    except Exception as e:
        return {"error": f"Gagal mengecek database: {str(e)}"}
    finally:
        release_connection(conn)
