#!/usr/bin/env php
<?php
/**
 * Simple PHP CLI runner
 *
 * Usage:
 *   php cli [group] [command] [--key=value ...]
 *
 * Behaviour:
 *   - Lists all groups and commands if no args.
 *   - Lists commands in a group if only group provided.
 *   - Runs ./lib/cli/[group]/[command].php with parsed args.
 */

require __DIR__ . '/main.inc.php';

$cliRoot = SITE_PATH . '/cli';

// --- Parse CLI args
array_shift($argv); // remove script name
$group   = $argv[0] ?? null;
$command = $argv[1] ?? null;

// --- Parse named parameters: --key=value or --key="value"
$args = [];
foreach ($argv as $arg) {
    if (preg_match('/^--([^=]+)=(.*)$/', $arg, $m)) {
        $args[$m[1]] = trim($m[2], "\"'");
    }
}

// --- Helper: extract first PHP comment as description
function getFileDescription($file) {
    $contents = file_get_contents($file);
    if (preg_match('/\/\*\*(.*?)\*\//s', $contents, $m)) {
        return trim(preg_replace('/\s*\*\s*/', ' ', $m[1]));
    }
    if (preg_match('/\/\/\s*(.+)/', $contents, $m)) {
        return trim($m[1]);
    }
    return '(no description)';
}

// --- Case 1: No args → list all groups + commands
if (!$group) {
    echo "Available command groups:\n";
    foreach (glob("$cliRoot/*", GLOB_ONLYDIR) as $dir) {
        $g = basename($dir);
        echo "  [$g]\n";
        foreach (glob("$dir/*.php") as $file) {
            $c = basename($file, '.php');
            echo "    - $c: " . getFileDescription($file) . "\n";
        }
    }
    exit(0);
}

// --- Case 2: Group only → list commands
$groupPath = "$cliRoot/$group";
if ($group && !$command) {
    if (!is_dir($groupPath)) {
        fwrite(STDERR, "❌ Group '$group' not found.\n");
        exit(1);
    }
    echo "Commands in group '$group':\n";
    foreach (glob("$groupPath/*.php") as $file) {
        $c = basename($file, '.php');
        echo "  - $c: " . getFileDescription($file) . "\n";
    }
    exit(0);
}

// --- Case 3: Run specific command
$commandFile = "$groupPath/$command.php";
if (!is_file($commandFile)) {
    fwrite(STDERR, "❌ Command '$group $command' not found.\n");
    exit(1);
}

// Make args available in command file
$_CLI_ARGS = $args;

require $commandFile;
