<?php
declare(strict_types=1);

require_once __DIR__ . '/yamn_config.php';

/** Encode a plaintext message with the local YAMN encoder binary. */
function encodeYamnMessage(array $request): array
{
    $encoder = yamnConfig('YAMN_ENCODER', '/usr/local/bin/yamn-encode');
    $keyring = yamnConfig('YAMN_PUBRING', '/opt/yamn-master/pubring.mix');
    if (!is_executable($encoder)) {
        return ['success' => false, 'error' => 'YAMN encoder is not available'];
    }
    $request['public_keyring'] = $keyring;
    try {
        $input = json_encode($request, JSON_THROW_ON_ERROR);
    } catch (JsonException $exception) {
        return ['success' => false, 'error' => 'Unable to encode YAMN request'];
    }

    $descriptors = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
    $process = proc_open([$encoder], $descriptors, $pipes);
    if (!is_resource($process)) {
        return ['success' => false, 'error' => 'Unable to start YAMN encoder'];
    }
    fwrite($pipes[0], $input);
    fclose($pipes[0]);
    $stdout = stream_get_contents($pipes[1]);
    fclose($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[2]);
    $status = proc_close($process);

    $response = json_decode($stdout, true);
    if ($status !== 0 || !is_array($response) || ($response['success'] ?? false) !== true) {
        return ['success' => false, 'error' => 'YAMN encoding failed'];
    }
    if (!isset($response['entry_address'], $response['envelope']) || !is_string($response['envelope'])) {
        return ['success' => false, 'error' => 'Invalid response from YAMN encoder'];
    }
    return ['success' => true, 'entry_address' => $response['entry_address'], 'envelope' => $response['envelope']];
}
