<?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/logger.php';
require_once __DIR__ . '/../src/storage.php';
require_once __DIR__ . '/../src/bitrix.php';
require_once __DIR__ . '/../src/bitrix_bot.php';

$options = getopt('', ['dialog-id:', 'message:', 'help']);
if (isset($options['help']) || empty($options['dialog-id']) || empty($options['message'])) {
    echo "Usage: php tools/send_bot_message.php --dialog-id=162100 --message=\"Test\"\n";
    exit(isset($options['help']) ? 0 : 1);
}

try {
    $result = sendBitrixBotMessage((string) $options['dialog-id'], (string) $options['message']);
    echo json_encode([
        'ok' => true,
        'bot_id' => (int) config('BITRIX_AI_BOT_ID', 0),
        'dialog_id' => (string) $options['dialog-id'],
        'result' => $result,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL;
} catch (Throwable $exception) {
    fwrite(STDERR, json_encode([
        'ok' => false,
        'bot_id' => (int) config('BITRIX_AI_BOT_ID', 0),
        'dialog_id' => (string) $options['dialog-id'],
        'error' => $exception->getMessage(),
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL);
    exit(1);
}
