<?php
declare(strict_types=1);
require __DIR__ . '/bootstrap.php';

use Acbr\Async\AsyncEmitter;
use Acbr\Configuration;
use Acbr\Emitter;

$emitter = null;
$async = null;
$exitCode = 0;
try {
    $emitter = new Emitter(new Configuration('11222333000181', 'CE', modelo: 55, ambiente: 2), timeoutMs: 10000);
    $async = new AsyncEmitter($emitter, capacity: 4, timeoutMs: 15000);
    $future = $async->gerarXml(acbrExampleDocument());
    $generated = $future->await();
    acbrExamplePrint($generated);
    if (!$generated->sucesso() || $generated->xml() === null) {
        throw new RuntimeException('Geracao offline falhou.');
    }
    // XML não assinado pode falhar no schema; isto não chama a SEFAZ.
    $validated = $async->validar($generated->xml())->await();
    acbrExamplePrint($validated);
} catch (Throwable $error) {
    acbrExampleError($error);
    $exitCode = 1;
} finally {
    try {
        $async?->fechar();
    } catch (Throwable $cleanupError) {
        acbrExampleError($cleanupError);
        $exitCode = 1;
    }
    $emitter?->fechar();
}
exit($exitCode);
