<?php

namespace app\process;

use app\service\Embedding\ChunkEmbeddingRepository;
use app\service\Search\ChunkSearchIndexRepository;
use app\service\Task\ProofDbTaskQueue;
use Throwable;

class ProofDbTaskDispatcher
{
    private ProofDbTaskQueue $queue;
    private ChunkEmbeddingRepository $embeddings;
    private ChunkSearchIndexRepository $searchIndex;

    public function __construct()
    {
        $this->queue = new ProofDbTaskQueue();
        $this->embeddings = new ChunkEmbeddingRepository();
        $this->searchIndex = new ChunkSearchIndexRepository();
    }

    public function onWorkerStart(): void
    {
        while (true) {
            $this->dispatchOnce();
            sleep($this->queue->dispatcherIntervalSeconds());
        }
    }

    private function dispatchOnce(): void
    {
        try {
            foreach ($this->embeddings->queuePendingArchiveTasks($this->queue->dispatcherBatchSize()) as $archiveUid) {
                $this->queue->push([
                    'task_type' => 'embedding',
                    'target_type' => 'archive',
                    'target_uid' => $archiveUid,
                    'attempt' => 1,
                    'queued_at' => date(DATE_ATOM),
                ]);
            }

            foreach ($this->searchIndex->queuePendingArchiveTasks($this->queue->dispatcherBatchSize()) as $archiveUid) {
                $this->queue->push([
                    'task_type' => 'search_index',
                    'target_type' => 'archive',
                    'target_uid' => $archiveUid,
                    'attempt' => 1,
                    'queued_at' => date(DATE_ATOM),
                ]);
            }
        } catch (Throwable $exception) {
            sleep($this->queue->idleSleepSeconds());
        }
    }
}
