#!/usr/bin/env php
<?php



declare(strict_types=1);

if (php_sapi_name() !== 'cli') {
    echo "CLI only\n";
    exit(1);
}

$batchId = $argv[1] ?? '';
if ($batchId === '' || !preg_match('/^[a-f0-9]{8,40}$/', $batchId)) {
    echo "valid batch_id required\n";
    exit(1);
}

require dirname(__DIR__) . '/config/php-guard.php';  
require dirname(__DIR__) . '/config/app.php';
Database::reconnect();
@set_time_limit(0);
@ignore_user_abort(true);

$tmpDir = APP_ROOT . '/storage/tmp';
$jobFile = $tmpDir . '/gallery-ai-job-' . $batchId . '.json';
$progressFile = $tmpDir . '/gallery-ai-progress-' . $batchId . '.json';
if (!is_file($jobFile)) {
    exit(0);
}

 
$lockKey = 'gallery_ai_' . $batchId;
$lk = Database::fetchOne('SELECT GET_LOCK(?, 0) AS l', [$lockKey]);
if (!$lk || (int) $lk['l'] !== 1) {
    exit(0);
}

try {
    $job = json_decode((string) @file_get_contents($jobFile), true);
    $albumIds = (is_array($job) && isset($job['album_ids']) && is_array($job['album_ids'])) ? $job['album_ids'] : [];
    $ai = (is_array($job) && isset($job['ai_settings']) && is_array($job['ai_settings'])) ? $job['ai_settings'] : [];

    if (empty($albumIds) || empty($ai['enabled'])) {
        @unlink($jobFile);
        Database::query('SELECT RELEASE_LOCK(?)', [$lockKey]);
        exit(0);
    }

    $total = count($albumIds);
    $doneN = 0;
    @file_put_contents($progressFile, json_encode(['total' => $total, 'done' => 0, 'updated' => date('c')]));

    foreach ($albumIds as $aid) {
        $aid = (int) $aid;
        if ($aid > 0) {
            try {
                CatalogueProcessor::applyAlbumAi($aid, $ai);
            } catch (\Throwable $e) {
                error_log('gallery-ai-worker: album ' . $aid . ' failed: ' . $e->getMessage());
            }
        }
        $doneN++;
        @file_put_contents($progressFile, json_encode(['total' => $total, 'done' => $doneN, 'updated' => date('c')]));
    }

    @unlink($jobFile);
    @unlink($progressFile);
} finally {
    Database::query('SELECT RELEASE_LOCK(?)', [$lockKey]);
}

exit(0);
