<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Helpers\InstallationLogger;

class ViewInstallationLog extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'installation:log {--lines=50 : Number of lines to show} {--clear : Clear the installation log}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'View or clear installation logs';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        if ($this->option('clear')) {
            InstallationLogger::clearLog();
            $this->info('Installation log cleared successfully.');
            return 0;
        }

        $lines = (int) $this->option('lines');
        $logPath = InstallationLogger::getLogPath();

        if (!file_exists($logPath)) {
            $this->error('Installation log file not found at: ' . $logPath);
            return 1;
        }

        $this->info('Installation Log (last ' . $lines . ' lines):');
        $this->info('Log file: ' . $logPath);
        $this->info(str_repeat('=', 80));

        $logLines = InstallationLogger::getLastLines($lines);

        foreach ($logLines as $line) {
            // Color code different log levels
            if (str_contains($line, 'ERROR:')) {
                $this->error($line);
            } elseif (str_contains($line, 'WARNING:')) {
                $this->warn($line);
            } elseif (str_contains($line, 'INFO:')) {
                $this->info($line);
            } else {
                $this->line($line);
            }
        }

        $this->info(str_repeat('=', 80));
        $this->info('Total lines in log: ' . count(file($logPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)));

        return 0;
    }
}