<?php

declare(strict_types=1);

namespace App\Framework\Console\Progress;

use App\Framework\Console\ConsoleColor;
use App\Framework\Console\ConsoleOutputInterface;

/**
 * Simple progress bar for console operations
 */
final readonly class ProgressBar
{
    public function __construct(
        private ConsoleOutputInterface $output,
        private int $width = 50
    ) {
    }

    public function render(float $progress, ?string $message = null): void
    {
        $progress = max(0.0, min(1.0, $progress));
        $completed = (int) round($this->width * $progress);
        $remaining = $this->width - $completed;

        $bar = '[' . str_repeat('=', $completed) . str_repeat(' ', $remaining) . ']';
        $percentage = (int) round($progress * 100);

        $output = "{$bar} {$percentage}%";

        if ($message) {
            $output .= " - {$message}";
        }

        $this->output->write("\r{$output}", ConsoleColor::CYAN);
    }

    public function clear(): void
    {
        $this->output->write("\r" . str_repeat(' ', $this->width + 20) . "\r");
    }

    public function finish(?string $message = null): void
    {
        $this->render(1.0, $message);
        $this->output->write("\n");
    }
}
