"""Analysis task worker — polls Redis queue and processes tasks."""

import time

from app.db.session import SessionLocal
from app.queue.analysis_queue import get_analysis_queue
from app.services.analysis import process_analysis_task


def run_worker(poll_timeout: int = 5) -> None:
    queue = get_analysis_queue()
    print("Analysis worker started · waiting for tasks…")
    while True:
        task_id = queue.pop(timeout=poll_timeout)
        if task_id is None:
            continue
        db = SessionLocal()
        try:
            task = process_analysis_task(db, task_id)
            if task:
                print(f"Processed task #{task_id} -> {task.status}")
        except Exception as exc:
            print(f"Failed task #{task_id}: {exc}")
        finally:
            db.close()


if __name__ == "__main__":
    run_worker()
