<?php

namespace App\Console\Commands;

use App\Jobs\GenerateLyricsJob;
use App\Models\Video;
use App\Services\NasSyncService;
use Illuminate\Console\Command;

/**
 * Backfill synced lyrics for existing songs. New uploads generate automatically;
 * this covers the catalogue that predates the feature.
 *
 *   php artisan lyrics:generate 163          # one video (primary + every track)
 *   php artisan lyrics:generate --all         # every music video missing lyrics
 *   php artisan lyrics:generate --all --force # regenerate even if a file exists
 */
class GenerateLyrics extends Command
{
    protected $signature = 'lyrics:generate {video? : Video id} {--all : All music videos} {--force : Regenerate even when lyrics already exist}';
    protected $description = 'Generate word-level synced lyrics for songs (dispatched to the video-processing queue)';

    public function handle(NasSyncService $nas): int
    {
        $force = (bool) $this->option('force');

        if ($videoId = $this->argument('video')) {
            $video = Video::find($videoId);
            if (! $video) {
                $this->error("Video #{$videoId} not found.");
                return self::FAILURE;
            }
            $videos = collect([$video]);
        } elseif ($this->option('all')) {
            $videos = Video::where('type', 'music')->get();
        } else {
            $this->error('Pass a video id or --all.');
            return self::FAILURE;
        }

        $dispatched = 0;
        foreach ($videos as $video) {
            $video->loadMissing('audioTracks');

            if ($force || ! is_array($nas->getLyrics($video, null))) {
                GenerateLyricsJob::dispatch($video->id, null)->onConnection('database');
                $dispatched++;
            }
            foreach ($video->audioTracks as $track) {
                if ($force || ! is_array($nas->getLyrics($video, $track))) {
                    GenerateLyricsJob::dispatch($video->id, $track->id)->onConnection('database');
                    $dispatched++;
                }
            }
            $this->line("Queued lyrics for #{$video->id} — {$video->title}");
        }

        $this->info("Dispatched {$dispatched} lyrics job(s) to the video-processing queue.");
        return self::SUCCESS;
    }
}
