import sqlite3
import os

def main():
    # Die Datenbank liegt nach der Aufraeumaktion im data/ Ordner
    db_path = os.path.join("data", "connector_queue.db")
    
    if not os.path.exists(db_path):
        print(f"ERROR: Database not found at {db_path}")
        # Fallback fuer den Fall, dass das Skript im Root oder in einem Unterordner ausgefuehrt wird
        db_path = "connector_queue.db"
        if not os.path.exists(db_path):
            print(f"ERROR: Fallback database also not found at {db_path}")
            return

    try:
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()

        # Zaehlen, wie viele Jobs betroffen sind (FAILED, SKIPPED, PROCESSING)
        cursor.execute("SELECT COUNT(*) FROM jobs WHERE status IN ('FAILED', 'SKIPPED', 'PROCESSING')")
        count = cursor.fetchone()[0]

        if count == 0:
            print("No failed, skipped or stuck processing jobs found to requeue.")
            return

        print(f"Found {count} jobs (FAILED/SKIPPED/PROCESSING) in {db_path}. Re-queueing them for re-evaluation...")

        # Alle betroffenen Jobs auf PENDING zuruecksetzen
        cursor.execute("UPDATE jobs SET status = 'PENDING', error_msg = NULL, next_try_at = NULL WHERE status IN ('FAILED', 'SKIPPED', 'PROCESSING')")
        conn.commit()

        print(f"✅ Success! {cursor.rowcount} jobs have been re-queued for processing.")

    except sqlite3.Error as e:
        print(f"Database error: {e}")
    finally:
        if 'conn' in locals() and conn:
            conn.close()

if __name__ == "__main__":
    main()
