#!/usr/bin/env php
<?php

declare(strict_types=1);

// AI toolkit administration CLI (no Laravel, no core). Usage:
//   php bin/ai set-config KEY VALUE   (enabled, provider, base_url, api_key, model, timeout)
//   php bin/ai get-config KEY         (api_key is masked)
//   php bin/ai status
//   php bin/ai review --json='{"first_name":"A",...}'
//   php bin/ai improve --kind=service --text="..."
//   php bin/ai price --samples=100,150,200

spl_autoload_register(static function (string $class): void {
    if (str_starts_with($class, 'AiToolkit\\')) {
        $file = __DIR__ . '/../src/' . str_replace('\\', '/', substr($class, 10)) . '.php';
        if (is_file($file)) {
            require $file;
        }
    }
});

use AiToolkit\AiConfig;
use AiToolkit\DescriptionAssistant;
use AiToolkit\PricingAdvisor;
use AiToolkit\ProfileReviewer;

$conf = getenv('AITOOLKIT_CONF') ?: __DIR__ . '/../storage/ai.json';
$config = new AiConfig($conf);

$command = $argv[1] ?? 'help';
$opts = [];
foreach (array_slice($argv, 2) as $arg) {
    if (str_starts_with($arg, '--')) {
        $pair = explode('=', substr($arg, 2), 2);
        $opts[$pair[0]] = $pair[1] ?? true;
    } else {
        $opts['#'][] = $arg;
    }
}

$fail = static function (string $msg): never {
    fwrite(STDERR, "error: {$msg}\n");
    exit(1);
};

$client = static function () use ($config, $fail) {
    if (!$config->enabled()) {
        $fail('AI endpoint not configured — set base_url, model and api_key first (enabled=1).');
    }

    return $config->client();
};

switch ($command) {
    case 'set-config':
        if (count($opts['#'] ?? []) < 2) {
            $fail('usage: ai set-config KEY VALUE');
        }
        [$key, $value] = $opts['#'];
        $allowed = ['enabled', 'provider', 'base_url', 'api_key', 'model', 'timeout'];
        if (!in_array($key, $allowed, true)) {
            $fail('KEY must be one of: ' . implode(', ', $allowed));
        }
        $config->set($key, (string) $value);
        echo "{$key} set\n";
        break;

    case 'get-config':
        $key = $opts['#'][0] ?? $fail('usage: ai get-config KEY');
        $value = $config->get($key);
        echo $key === 'api_key' && $value !== '' ? substr($value, 0, 4) . '****' . "\n" : $value . "\n";
        break;

    case 'status':
        echo 'enabled: ' . ($config->enabled() ? 'yes (deterministic + LLM polish)' : 'no (deterministic only)') . "\n";
        echo 'provider: ' . $config->get('provider', '(unset)') . "\n";
        echo 'model: ' . ($config->resolvedModel() !== '' ? $config->resolvedModel() : '(unset)') . "\n";
        echo 'endpoint: ' . ($config->resolvedBaseUrl() !== '' ? '(set)' : '(unset)') . "\n";
        break;

    case 'providers':
        echo implode("\n", AiToolkit\AiConfig::providers()) . "\n";
        break;

    case 'review':
        $profile = json_decode((string) ($opts['json'] ?? '{}'), true);
        if (!is_array($profile)) {
            $fail('--json must be a JSON object');
        }
        $review = (new ProfileReviewer($config->enabled() ? $client() : null))->review($profile);
        echo "score: {$review['score']} ({$review['source']})\n";
        foreach ($review['suggestions'] as $suggestion) {
            echo "- {$suggestion}\n";
        }
        break;

    case 'improve':
        $text = (string) ($opts['text'] ?? '');
        if ($text === '') {
            $fail('--text is required');
        }
        $result = (new DescriptionAssistant($config->enabled() ? $client() : null))
            ->assist((string) ($opts['kind'] ?? 'draft'), $text);
        echo "source: {$result['source']}\n";
        if ($result['improved'] !== null) {
            echo $result['improved'] . "\n";
        }
        foreach ($result['tips'] as $tip) {
            echo "- {$tip}\n";
        }
        break;

    case 'price':
        $samples = array_map('floatval', explode(',', (string) ($opts['samples'] ?? '')));
        $band = (new PricingAdvisor())->suggest([], $samples);
        echo "source: {$band['source']}\n";
        if ($band['mid'] !== null) {
            echo "low: {$band['low']}, mid: {$band['mid']}, high: {$band['high']}\n";
        }
        foreach ($band['tips'] as $tip) {
            echo "- {$tip}\n";
        }
        break;

    default:
        echo "usage: ai {set-config|get-config|status|providers|review|improve|price}\n";
        exit($command === 'help' ? 0 : 1);
}
