<?php

declare(strict_types=1);

require __DIR__ . '/../vendor/autoload.php';
$app = require __DIR__ . '/../bootstrap/app.php';
$app->make(Illuminate\Contracts\Console\Kernel::class)->bootstrap();

use Illuminate\Support\Facades\DB;

function printSection($title) {
    echo "\n===== $title =====\n";
}

printSection('Recent queued jobs (jobs table)');
$jobs = DB::table('jobs')->where('payload', 'like', '%AutoTagArtworkJob%')->orderByDesc('id')->limit(10)->get();
if (count($jobs) === 0) {
    echo "No queued AutoTagArtworkJob entries found.\n";
} else {
    foreach ($jobs as $j) {
        echo "--- job id: {$j->id} | queued_at: " . ($j->available_at ?? $j->created_at ?? '') . "\n";
        $payload = isset($j->payload) ? $j->payload : '';
        echo substr($payload, 0, 2000) . "\n\n";
    }
}

printSection('Recent failed jobs (failed_jobs table)');
$failed = DB::table('failed_jobs')->where('payload', 'like', '%AutoTagArtworkJob%')->orderByDesc('id')->limit(10)->get();
if (count($failed) === 0) {
    echo "No failed AutoTagArtworkJob entries found.\n";
} else {
    foreach ($failed as $f) {
        echo "--- failed id: {$f->id} | connection: {$f->connection} | failed_at: {$f->failed_at}\n";
        $payload = isset($f->payload) ? $f->payload : '';
        echo substr($payload, 0, 2000) . "\n\n";
    }
}

printSection('Recent Laravel logs (last 200 lines)');
$logs = glob(__DIR__ . '/../storage/logs/*.log');
if ($logs === false || count($logs) === 0) {
    echo "No log files found.\n";
} else {
    usort($logs, function($a, $b){ return filemtime($b) <=> filemtime($a); });
    $latest = $logs[0];
    echo "Latest log: " . basename($latest) . "\n\n";
    $lines = file($latest, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    if ($lines === false) {
        echo "Unable to read log file.\n";
    } else {
        $tail = array_slice($lines, -200);
        foreach ($tail as $line) {
            echo $line . "\n";
        }
    }
}

echo "\nDone.\n";
