<?php
declare(strict_types=1);

require_once __DIR__ . '/yamn_config.php';

/**
 * Queue an already encrypted YAMN envelope with the local Rust Nym sender.
 *
 * The handoff callback runs only after the persistent sender has accepted the
 * envelope into its bounded in-memory queue. The daemon is the sole owner of
 * the Nym client storage and never writes queued envelopes to disk.
 */
function sendNymEnvelope(
    string $payload,
    int $copies = 1,
    ?string $selectedEntryAddress = null,
    ?callable $onHandoff = null
): array
{
    $socketPath = yamnConfig('YAMN_NYM_SOCKET', '/run/yamnweb/nym-sender.sock');
    $entryAddress = $selectedEntryAddress ?? yamnConfig('YAMN_ENTRY_ADDRESS');

    if (
        dirname($socketPath) !== '/run/yamnweb'
        || basename($socketPath) === ''
        || str_contains($socketPath, "\0")
    ) {
        return ['success' => false, 'error' => 'Nym sender socket is not configured correctly'];
    }
    if ($entryAddress === '' || strlen($entryAddress) > 320 || preg_match('/[\r\n\0\s]/', $entryAddress)) {
        return ['success' => false, 'error' => 'YAMN entry address is not configured'];
    }
    if ($copies !== 1) {
        return ['success' => false, 'error' => 'Multiple copies are not enabled for Nym'];
    }
    if ($payload === '' || strlen($payload) > 65536 || str_contains($payload, "\0")) {
        return ['success' => false, 'error' => 'Invalid encrypted YAMN envelope'];
    }

    try {
        $input = json_encode([
            'entry_address' => $entryAddress,
            'payload' => $payload,
        ], JSON_THROW_ON_ERROR);
    } catch (JsonException $exception) {
        return ['success' => false, 'error' => 'Unable to encode Nym request'];
    }

    $errno = 0;
    $error = '';
    $socket = @stream_socket_client(
        'unix://' . $socketPath,
        $errno,
        $error,
        3,
        STREAM_CLIENT_CONNECT
    );
    if (!is_resource($socket)) {
        return ['success' => false, 'error' => 'Nym sender is not available'];
    }
    stream_set_timeout($socket, 5);

    $inputLength = strlen($input);
    $offset = 0;
    while ($offset < $inputLength) {
        $written = fwrite($socket, substr($input, $offset));
        if ($written === false || $written === 0) {
            break;
        }
        $offset += $written;
    }
    if ($offset !== $inputLength) {
        fclose($socket);
        return ['success' => false, 'error' => 'Unable to queue envelope with Nym sender'];
    }
    if (!stream_socket_shutdown($socket, STREAM_SHUT_WR)) {
        fclose($socket);
        return ['success' => false, 'error' => 'Unable to finish Nym queue request'];
    }

    $responseText = stream_get_contents($socket, 4096);
    $metadata = stream_get_meta_data($socket);
    fclose($socket);
    if (($metadata['timed_out'] ?? false) === true || !is_string($responseText)) {
        return ['success' => false, 'error' => 'Nym sender did not accept the queue request'];
    }
    $response = json_decode($responseText, true);
    if (!is_array($response) || ($response['success'] ?? false) !== true) {
        $queueError = is_array($response) && is_string($response['error'] ?? null)
            ? $response['error']
            : 'Nym sender rejected the queue request';
        return ['success' => false, 'error' => $queueError];
    }

    if ($onHandoff !== null) {
        $onHandoff();
    }

    return ['success' => true];
}
