import sqlite3
from datetime import datetime, timedelta

DB_PATH = "/app/connector_queue.db"

def clear_all_zombies():
    print("🧹 Cleaning up Zombie Jobs (PROCESSING for too long)...")
    # A job that is PROCESSING for more than 10 minutes is likely dead
    threshold = (datetime.utcnow() - timedelta(minutes=10)).strftime('%Y-%m-%d %H:%M:%S')
    
    with sqlite3.connect(DB_PATH) as conn:
        cursor = conn.cursor()
        
        # 1. Identify Zombies
        cursor.execute("SELECT id, updated_at FROM jobs WHERE status = 'PROCESSING' AND updated_at < ?", (threshold,))
        zombies = cursor.fetchall()
        
        if not zombies:
            print("✅ No zombies found.")
            return

        print(f"🕵️ Found {len(zombies)} zombie jobs.")
        for zid, updated in zombies:
            print(f"   - Zombie ID {zid} (Last active: {updated})")

        # 2. Kill them
        cursor.execute("UPDATE jobs SET status = 'FAILED', error_msg = 'Zombie cleared: Process timed out' WHERE status = 'PROCESSING' AND updated_at < ?", (threshold,))
        print(f"✅ Successfully cleared {cursor.rowcount} zombie(s).")

if __name__ == "__main__":
    clear_all_zombies()
