<?php
// cli/worker.php

declare(strict_types=1);

$services = require __DIR__ . '/../app/bootstrap.php';

$config = $services['config'];

$jobs = $services['jobs'];
$scanner = $services['scanner'];
$schema = $services['schema'];
$db = $services['db'];

$sleep = 2;
if (isset($config['app']['worker_sleep_seconds'])) {
  $sleep = (int)$config['app']['worker_sleep_seconds'];
}
if ($sleep < 1) $sleep = 1;

echo "scmedia-worker started (sleep={$sleep}s)\n";

for (;;) {
  $job = $jobs->fetchNextQueued();
  if (!$job) {
    sleep($sleep);
    continue;
  }

  $jobId = (int)$job['id'];
  $type = (string)$job['type'];

  echo "Picked job id={$jobId} type={$type}\n";

  try {
    $jobs->start($jobId);
    $jobs->log($jobId, 'info', "Worker started job type={$type}");

    if ($type === 'scan') {
      $scanner->runScanJob($jobId);
      $jobs->finish($jobId);
      $jobs->log($jobId, 'info', "Worker finished scan");
    } elseif ($type === 'db_reset') {
      $cfg = $config['app'] ?? [];
      if (empty($cfg['allow_db_reset'])) {
        throw new Exception("DB reset is disabled by config (app.allow_db_reset=false)");
      }

      $jobs->setProgress($jobId, 0, 1);
      $log = [];
      $schema->resetDatabase($log);
      foreach ($log as $line) {
        $jobs->log($jobId, 'info', (string)$line);
      }
      $jobs->setProgress($jobId, 1, 1);
      $jobs->finish($jobId);
    } elseif ($type === 'clear_index') {
      $jobs->setProgress($jobId, 0, 3);

      $db->exec("DELETE FROM items");
      $jobs->setProgress($jobId, 1, 3);
      $jobs->log($jobId, 'info', "items cleared");

      // Note: keep jobs table; we clear logs for old jobs only (optional)
      $db->exec("DELETE FROM job_logs WHERE job_id <> :id", [':id' => $jobId]);
      $jobs->setProgress($jobId, 2, 3);
      $jobs->log($jobId, 'info', "job_logs cleared (except current)");

      $jobs->setProgress($jobId, 3, 3);
      $jobs->finish($jobId);
    } else {
      throw new Exception("Unsupported job type: {$type}");
    }
  } catch (Throwable $e) {
    $jobs->log($jobId, 'error', $e->getMessage());
    $jobs->fail($jobId, $e->getMessage());
    fwrite(STDERR, "Job {$jobId} failed: " . $e->getMessage() . "\n");
  }

  sleep(1);
}
