<?php

namespace App\Console\Commands;

use App\Models\Server;
use App\Services\Audit\AuditRunner;
use Illuminate\Console\Command;

/**
 * CLI wrapper around AuditRunner. Same audit code as the autonomous
 * scheduler — runs once now and prints a summary instead of queuing.
 *
 * Usage:
 *   php artisan audit:run                                # all servers with stored creds
 *   php artisan audit:run dnsserver.hostseba.com         # one server, stored creds
 *   php artisan audit:run dnsserver.hostseba.com --user=root --password='...'
 */
class AuditRun extends Command
{
    protected $signature = 'audit:run
        {hostname? : Server hostname (omit to run all servers with stored creds)}
        {--user= : Override SSH user}
        {--password= : Override SSH password}
        {--key= : Override SSH key path}
        {--port=22 : SSH port override}';

    protected $description = 'Run the autonomous server health audit (heuristic, no AI). Same code path as the scheduler.';

    public function handle(AuditRunner $runner): int
    {
        $servers = $this->resolveServers();
        if ($servers->isEmpty()) {
            $this->error('No matching server.');
            return self::FAILURE;
        }

        foreach ($servers as $server) {
            $this->line("\n<fg=cyan>━━━ {$server->hostname} ({$server->ip}) ━━━</>");

            $override = array_filter([
                'user'     => $this->option('user'),
                'password' => $this->option('password'),
                'key'      => $this->option('key'),
                'port'     => (int) $this->option('port') ?: null,
            ], fn ($v) => $v !== null);

            $r = $runner->run($server, $override);

            if ($r['ok']) {
                $this->info("  ✓ {$r['findings']} findings ({$r['inserted']} new) · {$r['actions']} pending actions · metrics #{$r['metrics_id']}");
            } else {
                $this->error('  ✗ ' . $r['error']);
            }
        }
        return self::SUCCESS;
    }

    private function resolveServers()
    {
        if ($h = $this->argument('hostname')) {
            return Server::where('hostname', $h)->get();
        }
        return Server::whereNotNull('ssh_user')->get();
    }
}
