<?php
/**
 * Read config values 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 array_key_exists;
use function explode;
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 ConfigGetCommand extends Command
{
    public function getName(): string
    {
        return 'config:get';
    }

    public function getDescription(): string
    {
        return 'Get a config value from an ini file under storage/config';
    }

    public function getHelp(): string
    {
        return "Usage:\n"
            . "  php index.php config:get <relative_ini_path> <section> <key>\n"
            . "  php index.php config:get <relative_ini_path> <section.key>\n"
            . "\nExamples:\n"
            . "  php index.php config:get system/root.ini root username\n"
            . "  php index.php config:get system/root.ini root.password_hash\n";
    }

    protected function handle(array $args): int
    {
        $rel = trim((string)($args[0] ?? ''));
        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;
        }

        $section = '';
        $key = '';

        $arg1 = trim((string)($args[1] ?? ''));
        $arg2 = trim((string)($args[2] ?? ''));

        if ($arg1 === '') {
            $this->error('section/key is required');
            return 1;
        }

        if ($arg2 === '' && str_contains($arg1, '.')) {
            [$section, $key] = explode('.', $arg1, 2);
        } else {
            $section = $arg1;
            $key = $arg2;
        }

        $section = trim($section);
        $key = trim($key);

        if ($section === '' || $key === '') {
            $this->error('Both section and key are required');
            return 1;
        }

        if (!isset($data[$section]) || !is_array($data[$section]) || !array_key_exists($key, $data[$section])) {
            $this->error("Not found: [{$section}] {$key}");
            return 1;
        }

        $value = $data[$section][$key];
        $this->output((string)$value);
        return 0;
    }
}
