<?php

declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(403);
    echo "This script can be run only from CLI.\n";
    exit(1);
}

require_once __DIR__ . '/../src/config.php';
require_once __DIR__ . '/../src/storage.php';
require_once __DIR__ . '/../src/history.php';

$options = getopt('', ['dialog-id::', 'chat-id::', 'help']);
if (isset($options['help'])) {
    echo "Usage: php tools/show_history.php [--dialog-id=162100] [--chat-id=901615]\n";
    exit(0);
}

if (!empty($options['dialog-id']) || !empty($options['chat-id'])) {
    $context = [
        'dialog_id' => (string) ($options['dialog-id'] ?? ''),
        'chat_id' => (string) ($options['chat-id'] ?? ''),
    ];
    $result = [
        'key' => chatHistoryKey($context),
        'messages' => getChatHistory($context),
    ];
} else {
    $result = listChatHistories();
}

echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
