<?php

namespace App\Console\Commands;

use App\Services\HardwareSnapshot;
use App\Support\RigData;
use Illuminate\Console\Command;

class RigTelemetryCommand extends Command
{
    protected $signature = 'rig:telemetry {--collect : Re-read hardware + OBS profile (default: only refresh if file is missing)}';
    protected $description = 'Capture rig hardware + OBS profile snapshot → storage/data/telemetry.json';

    public function handle(HardwareSnapshot $snap, RigData $rig): int
    {
        $path = rtrim(config('rig.storage_data'), '/') . '/telemetry.json';

        if ($this->option('collect') || !is_file($path)) {
            $data = $snap->collect();
            @mkdir(dirname($path), 0775, true);
            file_put_contents(
                $path,
                json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) . "\n"
            );
            $this->info("  ✓ wrote {$path}");
        } else {
            $this->line("  · {$path} already exists — use --collect to re-read hardware.");
        }

        $current = $rig->telemetry();
        $this->line('');
        $this->line("    rig    = " . ($current['rig'] ?? '?'));
        $this->line("    cpu    = " . ($current['cpu']['model'] ?? '?'));
        if (!empty($current['gpu']['name'])) {
            $this->line("    gpu    = " . $current['gpu']['name']);
        }
        if (!empty($current['obs']['output']['w'])) {
            $this->line("    output = {$current['obs']['output']['w']}×{$current['obs']['output']['h']} @ {$current['obs']['fps']} fps");
        }
        return self::SUCCESS;
    }
}
