<?php
/** Send an already prepared YAMN payload through the local Katzenpost sender. */
function sendKatzenpostEnvelope(string $entryAddress, string $payload, int $copies = 1): array
{
    $sender = getenv('YAMN_KP_SENDER') ?: '/usr/local/bin/yamn-submit';
    $config = getenv('YAMN_KP_CONFIG') ?: '/etc/yamnweb/thinclient.toml';
    if (!is_executable($sender)) {
        return ['success' => false, 'error' => 'Katzenpost sender is not available'];
    }
    if (!filter_var($entryAddress, FILTER_VALIDATE_EMAIL) || !str_ends_with(strtolower($entryAddress), '@remailer.example')) {
        return ['success' => false, 'error' => 'Invalid YAMN entry address'];
    }
    if ($payload === '' || strlen($payload) > 65536) {
        return ['success' => false, 'error' => 'Invalid YAMN payload'];
    }

    $message = "To: {$entryAddress}\n" . $payload;
    if (!str_contains($message, "-----BEGIN REMAILER MESSAGE-----\n")) {
        $message = "To: {$entryAddress}\n\n-----BEGIN REMAILER MESSAGE-----\n" . $payload;
    }
    if ($copies !== 1) return ['success' => false, 'error' => 'Multiple copies are not enabled in the PoC'];
    $input = json_encode(['entry_address' => $entryAddress, 'message' => $message], JSON_THROW_ON_ERROR);
    $descriptor = [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']];
    $process = proc_open([$sender, '-config', $config, '-settle', '2s'], $descriptor, $pipes);
    if (!is_resource($process)) return ['success' => false, 'error' => 'Unable to start Katzenpost sender'];
    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);
    return $status === 0 ? ['success' => true] : ['success' => false, 'error' => 'Katzenpost submission failed'];
}
