ReprocessUnmatchedTvReleases   A
last analyzed

Complexity

Total Complexity 18

Size/Duplication

Total Lines 166
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 18
eloc 98
c 3
b 0
f 0
dl 0
loc 166
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
F handle() 0 138 17
1
<?php
2
3
namespace App\Console\Commands;
4
5
use App\Models\Category;
6
use App\Models\Release;
7
use App\Services\TvProcessing\TvProcessingPipeline;
8
use Illuminate\Console\Command;
9
use Illuminate\Support\Facades\Log;
10
11
class ReprocessUnmatchedTvReleases extends Command
12
{
13
    /**
14
     * The name and signature of the console command.
15
     *
16
     * @var string
17
     */
18
    protected $signature = 'tv:reprocess-unmatched
19
                            {--limit=0 : Limit the number of releases to process (0 = no limit)}
20
                            {--dry-run : Show how many releases would be processed without making changes}
21
                            {--debug : Show detailed debug information for each release}
22
                            {--sleep=0 : Sleep time in milliseconds between processing each release}';
23
24
    /**
25
     * The console command description.
26
     *
27
     * @var string
28
     */
29
    protected $description = 'Reprocess all TV releases that are not matched to any show in the database (videos_id = 0)';
30
31
    public function __construct()
32
    {
33
        parent::__construct();
34
    }
35
36
    /**
37
     * Execute the console command.
38
     */
39
    public function handle(): int
40
    {
41
        $limit = (int) $this->option('limit');
42
        $dryRun = (bool) $this->option('dry-run');
43
        $debug = (bool) $this->option('debug');
44
        $sleep = (int) $this->option('sleep');
45
46
        // Build query for unmatched TV releases (newest to oldest by adddate, then postdate)
47
        $query = Release::query()
48
            ->select(['id', 'guid', 'searchname', 'videos_id', 'tv_episodes_id', 'categories_id', 'adddate', 'postdate'])
49
            ->where('videos_id', 0)
50
            ->whereBetween('categories_id', [Category::TV_ROOT, Category::TV_OTHER])
51
            ->orderBy('adddate', 'desc')
0 ignored issues
show
Bug introduced by
'adddate' of type string is incompatible with the type Closure|Illuminate\Datab...\Database\Query\Builder expected by parameter $column of Illuminate\Database\Query\Builder::orderBy(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

51
            ->orderBy(/** @scrutinizer ignore-type */ 'adddate', 'desc')
Loading history...
52
            ->orderBy('postdate', 'desc');
53
54
        $totalCount = (clone $query)->count();
55
56
        if ($totalCount === 0) {
57
            $this->info('No unmatched TV releases found.');
58
            return self::SUCCESS;
59
        }
60
61
        $this->info("Found {$totalCount} unmatched TV release(s).");
62
63
        if ($limit > 0) {
64
            $query->limit($limit);
65
            $processCount = min($limit, $totalCount);
66
            $this->info("Processing limited to {$processCount} release(s).");
67
        } else {
68
            $processCount = $totalCount;
69
        }
70
71
        if ($dryRun) {
72
            $this->line("[Dry Run] Would process {$processCount} unmatched TV release(s).");
73
74
            // Show sample of releases that would be processed
75
            $sample = (clone $query)->limit(10)->get();
76
            if ($sample->isNotEmpty()) {
77
                $this->newLine();
78
                $this->info('Sample of releases to be processed:');
79
                $rows = $sample->map(fn ($release) => [
80
                    $release->id,
81
                    $release->guid,
82
                    mb_substr($release->searchname, 0, 60) . (strlen($release->searchname) > 60 ? '...' : ''),
83
                    $release->categories_id,
84
                ])->toArray();
85
                $this->table(['ID', 'GUID', 'Search Name', 'Category'], $rows);
86
            }
87
88
            return self::SUCCESS;
89
        }
90
91
        $this->info("Starting to process {$processCount} unmatched TV release(s)...");
92
        $this->newLine();
93
94
        $bar = $this->output->createProgressBar($processCount);
95
        $bar->setFormat(' %current%/%max% [%bar%] %percent:3s%% | Matched: %matched% | Failed: %failed% | Elapsed: %elapsed:6s%');
96
        $bar->setMessage('0', 'matched');
97
        $bar->setMessage('0', 'failed');
98
        $bar->start();
99
100
        $matched = 0;
101
        $failed = 0;
102
        $processed = 0;
103
104
        try {
105
            $pipeline = TvProcessingPipeline::createDefault(echoOutput: false);
106
107
            // Use cursor to iterate without chunking issues when ordering by non-id columns
108
            $cursor = $query->cursor();
109
110
            foreach ($cursor as $release) {
111
                if ($limit > 0 && $processed >= $limit) {
112
                    break;
113
                }
114
115
                try {
116
                    $result = $pipeline->processRelease($release, $debug);
117
118
                    if ($result['matched']) {
119
                        $matched++;
120
                        if ($debug) {
121
                            $this->newLine();
122
                            cli()->primary("Matched: {$release->searchname}");
123
                            $this->info('  Provider: ' . ($result['provider'] ?? 'Unknown'));
124
                            $this->info('  Video ID: ' . ($result['video_id'] ?? 'N/A'));
125
                            $this->info('  Episode ID: ' . ($result['episode_id'] ?? 'N/A'));
126
                        }
127
                    } else {
128
                        $failed++;
129
                        if ($debug) {
130
                            $this->newLine();
131
                            cli()->warning("No match: {$release->searchname}");
132
                        }
133
                    }
134
                } catch (\Throwable $e) {
135
                    $failed++;
136
                    Log::error("Error processing release {$release->guid}: " . $e->getMessage());
137
                    if ($debug) {
138
                        $this->newLine();
139
                        $this->error("Error processing {$release->searchname}: " . $e->getMessage());
140
                    }
141
                }
142
143
                $processed++;
144
                $bar->setMessage((string) $matched, 'matched');
145
                $bar->setMessage((string) $failed, 'failed');
146
                $bar->advance();
147
148
                if ($sleep > 0) {
149
                    usleep($sleep * 1000);
150
                }
151
            }
152
153
154
        } catch (\Throwable $e) {
155
            $bar->finish();
156
            $this->newLine();
157
            $this->error('Fatal error during processing: ' . $e->getMessage());
158
            Log::error('Fatal error in tv:reprocess-unmatched: ' . $e->getMessage() . "\n" . $e->getTraceAsString());
159
            return self::FAILURE;
160
        }
161
162
        $bar->finish();
163
        $this->newLine(2);
164
165
        $this->info('Processing complete!');
166
        $this->table(
167
            ['Total Processed', 'Matched', 'Not Matched', 'Match Rate'],
168
            [[
169
                number_format($processed),
170
                number_format($matched),
171
                number_format($failed),
172
                $processed > 0 ? round(($matched / $processed) * 100, 2) . '%' : '0%',
173
            ]]
174
        );
175
176
        return self::SUCCESS;
177
    }
178
}
179
180