<?php

declare(strict_types=1);

namespace App\Framework\Logging\Commands;

use App\Framework\Console\ConsoleCommand;
use App\Framework\Console\ConsoleInput;
use App\Framework\Console\ConsoleOutput;
use App\Framework\Console\ExitCode;
use App\Framework\Core\ValueObjects\Byte;
use App\Framework\Logging\LogRotator;

final readonly class RotateLogsCommand
{
    #[ConsoleCommand(name: "logs:rotate", description: "Rotiert Log-Dateien basierend auf Größe und Anzahl")]
    public function execute(ConsoleInput $input, ConsoleOutput $output): ExitCode
    {
        $output->writeLine('<info>Starting log rotation...</info>');

        // Standard Log-Pfade
        $logPaths = $this->getLogPaths();
        $rotator = LogRotator::production();

        $rotatedCount = 0;
        $totalSize = Byte::zero();

        foreach ($logPaths as $name => $path) {
            if (! file_exists($path)) {
                $output->writeLine("<comment>Skipping {$name}: File not found ({$path})</comment>");

                continue;
            }

            $beforeSize = Byte::fromBytes(filesize($path));
            $totalSize = $totalSize->add($beforeSize);

            if ($rotator->shouldRotate($path)) {
                $output->writeLine("<info>Rotating {$name} ({$path})</info>");

                if ($rotator->rotateLog($path)) {
                    $rotatedCount++;
                    $output->writeLine("<success>  ✓ Successfully rotated {$name}</success>");

                    // Zeige Rotation-Info
                    $info = $rotator->getRotationInfo($path);
                    $output->writeLine("    Current size: {$info['current_size']}");
                    $output->writeLine("    Rotated files: " . count($info['rotated_files']));
                } else {
                    $output->writeLine("<error>  ✗ Failed to rotate {$name}</error>");
                }
            } else {
                $output->writeLine("<comment>  → {$name} doesn't need rotation</comment>");
                $info = $rotator->getRotationInfo($path);
                $output->writeLine("    Current size: {$info['current_size']} / {$info['max_size']}");
            }
        }

        $output->writeLine('');
        $output->writeLine("<info>Rotation completed:</info>");
        $output->writeLine("  Files rotated: {$rotatedCount}");
        $output->writeLine("  Total log size: " . $totalSize->toHumanReadable());

        return ExitCode::SUCCESS;
    }

    private function getLogPaths(): array
    {
        $basePath = $_SERVER['DOCUMENT_ROOT'] ?? '/var/www/html';

        return [
            'app' => $basePath . '/public/logs/app.log',
            'mcp_debug' => $basePath . '/mcp_debug.log',
            'framework' => '/tmp/framework.log',
        ];
    }
}
