<?php
if (PHP_SAPI !== 'cli') { 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_qr_auth_worker.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';

$channel_id = isset($argv[1]) ? (int)$argv[1] : 0;
$attempt_id = isset($argv[2]) ? (string)$argv[2] : '';
if ($channel_id <= 0 || preg_match('/^[a-f0-9]{24}$/D', $attempt_id) !== 1) { exit(1); }

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\WhatsAppPersonalAuthService($registry))->runQrWorker($channel_id, $attempt_id);
    exit(!empty($result['success']) ? 0 : 1);
} catch (Throwable $error) {
    error_log('EASYCHAT_WHATSAPP_QR_ERROR=worker_failed');
    exit(1);
}
