<?php










if (PHP_SAPI !== 'cli') {
    http_response_code(404);
    exit(1);
}

ini_set('display_errors', '0');
ini_set('log_errors', '1');
define('DS', DIRECTORY_SEPARATOR);
$root = dirname(__DIR__);
if (!is_file($root . DS . 'config.php')) exit(1);

require_once $root . DS . 'core' . DS . 'runtime_reader_lock.php';
$easychat_runtime_reader_lock = easychat_runtime_reader_lock_acquire($root, false);
require_once $root . DS . 'library' . DS . 'request_context.php';
\EasyChat\Library\RequestContext::bootstrapServerDefaults([
    'HTTP_HOST' => 'localhost',
    'SCRIPT_NAME' => '/cli/wildberries_history_repair.php',
    'HTTPS' => 'off',
    'SERVER_PORT' => 80,
]);
require_once $root . DS . 'config.php';
require_once SITE_PATH . DS . 'core' . DS . 'autoload.php';

$options = getopt('', ['received-from:', 'received-to:', 'channel::', 'apply']);
$received_from = (string)($options['received-from'] ?? '');
$received_to = (string)($options['received-to'] ?? '');
$channel_id = (int)($options['channel'] ?? 0);
$apply = array_key_exists('apply', $options);

try {
    $registry = new Registry();
    $db = new DB(DB_DRIVER, DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE, DB_PORT);
    $registry->set('db', $db);
    (new EasyChat\Library\AppClock($registry))->syncDatabaseSessionTimezone();
    EasyChat\Library\InstallService::ensureRuntimeSchema($db, easychat_db_prefix());
    $result = (new EasyChat\Library\Messenger\Marketplace\WildberriesHistoryRepairService($registry))
        ->run($received_from, $received_to, $channel_id, $apply);
    fwrite(STDOUT, json_encode($result, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT) . PHP_EOL);
    exit(!empty($result['success']) ? 0 : 2);
} catch (Throwable $error) {
    fwrite(STDOUT, json_encode(['success' => false, 'error' => 'repair_bootstrap_failed']) . PHP_EOL);
    exit(2);
}
