<?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/cleanup.php';

$options = getopt('', ['execute', 'help']);
if (isset($options['help'])) {
    echo "Usage: php tools/delete_darex_ai.php [--execute]\n";
    exit(0);
}

$execute = isset($options['execute']);
$bots = listBitrixBots();
$matchedBots = [];
$botResults = [];

foreach ($bots as $bot) {
    if (!is_array($bot) || !darexBotMatches($bot)) {
        continue;
    }

    $botId = (int) ($bot['ID'] ?? 0);
    if ($botId <= 0) {
        continue;
    }

    $matchedBots[] = $bot;
    if ($execute) {
        $botResults[$botId] = unregisterBitrixBot($botId);
    }
}

$connectorId = (string) config('CONNECTOR_ID', 'darex_ai_whatsapp');
$connectorResult = null;
if ($execute && $connectorId !== '') {
    $connectorResult = unregisterBitrixConnector($connectorId);
}

cliPrintJson([
    'dry_run' => !$execute,
    'matched_bots' => $matchedBots,
    'bot_delete_results' => $botResults,
    'connector_id' => $connectorId,
    'connector_delete_result' => $connectorResult,
]);
