<?php
 
if (PHP_SAPI !== 'cli') { http_response_code(404); exit(1); }
ignore_user_abort(true);
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/whatsapp_polling.php',
    'HTTPS' => 'off', 'HTTP_X_FORWARDED_PROTO' => '', 'HTTP_X_FORWARDED_SSL' => '', 'SERVER_PORT' => 80,
]);
require_once $root . DS . 'config.php';
require_once SITE_PATH . DS . 'core' . DS . 'autoload.php';

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\WhatsAppPersonalWorker($registry))->run(['source' => 'dedicated_cron']);
    if (empty($result['success'])) {
        fwrite(STDERR, 'WhatsApp polling failed: ' . preg_replace('/[^a-z0-9_]/', '', (string)($result['error'] ?? 'worker_failed')) . PHP_EOL);
        exit(1);
    }
    exit(0);
} catch (Throwable $error) {
    fwrite(STDERR, 'WhatsApp polling failed: worker_failed' . PHP_EOL);
    exit(1);
}
