<?php
/**
 * Show ini config content from storage/config/*.ini.
 *
 * @package Flowaxy\Interface\CLI\Commands
 */

declare(strict_types=1);

namespace Flowaxy\Interface\CLI\Commands;

use Flowaxy\Core\System\PathResolver;
use Flowaxy\Interface\CLI\Command;

use function file_exists;
use function is_array;
use function parse_ini_file;
use function str_contains;
use function str_replace;
use function trim;

final class ConfigShowCommand extends Command
{
    public function getName(): string
    {
        return 'config:show';
    }

    public function getDescription(): string
    {
        return 'Show parsed ini config (sections/keys) from storage/config';
    }

    public function getHelp(): string
    {
        return "Usage:\n"
            . "  php index.php config:show <relative_ini_path>\n"
            . "  php index.php config:show <relative_ini_path> <section>\n";
    }

    protected function handle(array $args): int
    {
        $rel = trim((string)($args[0] ?? ''));
        $sectionFilter = trim((string)($args[1] ?? ''));

        if ($rel === '' || str_contains($rel, '..')) {
            $this->error('relative_ini_path is required and must not contain ".."');
            return 1;
        }

        $file = PathResolver::storageConfig() . DS . str_replace(['/', '\\'], DS, $rel);
        if (!file_exists($file)) {
            $this->error("Config file not found: {$file}");
            return 1;
        }

        $data = parse_ini_file($file, true, INI_SCANNER_RAW);
        if (!is_array($data)) {
            $this->error("Failed to parse ini: {$file}");
            return 1;
        }

        foreach ($data as $section => $pairs) {
            if ($sectionFilter !== '' && $sectionFilter !== (string)$section) {
                continue;
            }
            if (!is_array($pairs)) {
                continue;
            }
            $this->output('[' . $section . ']');
            foreach ($pairs as $k => $v) {
                $this->output('  ' . $k . ' = ' . (string)$v);
            }
            $this->output('');
        }

        return 0;
    }
}
