import time
import logging
import sys
import os

# Ensure brynq is in path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from brynq.task_queue import dequeue, complete_task
from brynq.llm_router import chat

logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")

def run_daemon():
    logging.info("========================================================")
    logging.info("COO-NODE | WORKER DAEMON | ONLINE & POLLING")
    logging.info("========================================================")
    
    worker_id = f"worker_{os.getpid()}"
    
    while True:
        try:
            # Check for high priority tasks first
            task = dequeue(agent_id=worker_id)
            if task:
                task_id = task['task_id']
                prompt = task.get('prompt', 'Perform background analysis.')
                
                logging.info(f"[WORKER] Picked up Task ID: {task_id} | Priority: {task.get('priority')} | Prompt: {prompt[:50]}...")
                
                # Execute via LLM Router using best available quality model
                try:
                    messages = [{"role": "user", "content": prompt}]
                    result = chat(backend="auto", model="auto", messages=messages)
                    logging.info(f"[WORKER] Task ID: {task_id} executed successfully.")
                except Exception as e:
                    result = f"[ERROR] Execution failed: {str(e)}"
                    logging.error(f"[WORKER] Task ID: {task_id} failed: {e}")
                
                complete_task(task_id, result)
            else:
                time.sleep(3) # Polling interval
        except Exception as e:
            logging.error(f"[WORKER] Daemon loop error: {e}")
            time.sleep(5)

if __name__ == "__main__":
    run_daemon()
