<?php
/**
 * Smoke test del SummaryService end-to-end.
 * Uso: php bin/ai_summary_smoke
 */
if (php_sapi_name() !== 'cli') {
    die("CLI only.\n");
}

define('BASE_PATH', dirname(__DIR__) . DIRECTORY_SEPARATOR);
require BASE_PATH . 'core/helpers/Env.php';
Env::load(BASE_PATH . '.env');
require BASE_PATH . 'app/config/Config.php';
require BASE_PATH . 'app/config/ConfigEnv.php';
require BASE_PATH . 'vendor/autoload.php';
ConfigEnv::applyEnvironmentOverrides();

use Klee\Core\Ai\LlmClient;
use Klee\Core\Ai\SummaryService;

$cfg = ConfigEnv::getAiConfiguration();
$cn = ConfigEnv::getConnectionConfig('klee');
$pdo = new PDO("mysql:host={$cn['host']};dbname={$cn['dbname']};charset=utf8mb4", $cn['user'], $cn['password'], array(
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
));

$llm = new LlmClient($cfg);
$svc = new SummaryService($llm, $pdo, (int)($cfg['tenantId'] ?? 1));

$from = date('Y-m-d 00:00:00', strtotime('-7 days'));
$to = date('Y-m-d 23:59:59');
echo "Ventana: $from .. $to\n";

$agg = $svc->aggregateAlertas($from, $to);
echo "Agregado: total={$agg['total']} criticas={$agg['criticas']} no_atendidas={$agg['no_atendidas']}\n";

$result = $svc->summarizeAlertas($from, $to, false);
echo "----- RESUMEN -----\n";
echo "headline: " . ($result['headline'] ?? '') . "\n";
echo "summary : " . ($result['summary'] ?? '') . "\n";
echo "severity: " . ($result['severity'] ?? '') . "\n";
echo "model   : " . ($result['_model'] ?? '') . "\n";
echo "cached  : " . (!empty($result['_cached']) ? 'YES' : 'NO') . "\n";
if (isset($result['_tokens'])) {
    echo "tokens  : in={$result['_tokens']['tokens_in']} out={$result['_tokens']['tokens_out']}\n";
}
if (isset($result['_cost_usd'])) {
    echo "cost USD: " . $result['_cost_usd'] . "\n";
}
echo "key_points: \n";
foreach (($result['key_points'] ?? array()) as $kp) {
    echo "  - $kp\n";
}
echo "actions: \n";
foreach (($result['recommended_actions'] ?? array()) as $a) {
    echo "  - $a\n";
}
echo "[ok] SummaryService funcional.\n";
