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

use Acbr\CertificateA1;
use Acbr\Configuration;
use Acbr\Emitter;

$emitter = null;
$exitCode = 0;
try {
    // Somente A1 sintético efêmero de laboratório; nenhum PFX acompanha os exemplos.
    if (getenv('ACBR_CERTIFICADO_SINTETICO') !== '1') {
        throw new RuntimeException('Declare explicitamente o uso de certificado sintetico.');
    }
    $path = getenv('ACBR_A1_PATH');
    $password = getenv('ACBR_A1_PASSWORD');
    if ($path === false || $path === '' || $password === false) {
        throw new RuntimeException('Configure o A1 sintetico por fonte segura.');
    }
    $certificate = CertificateA1::fromFile($path, $password);
    $emitter = new Emitter(
        new Configuration('11222333000181', 'CE', modelo: 55, ambiente: 2, certificado: $certificate),
        timeoutMs: 10000,
    );
    $generated = $emitter->gerarXml(acbrExampleDocument());
    if (!$generated->sucesso() || $generated->xml() === null) {
        acbrExamplePrint($generated);
        throw new RuntimeException('Geracao sintetica falhou.');
    }
    $signed = $emitter->assinar($generated->xml());
    acbrExamplePrint($signed);
    if (!$signed->sucesso() || $signed->xml() === null) {
        throw new RuntimeException('Assinatura sintetica falhou.');
    }
    $validated = $emitter->validar($signed->xml());
    acbrExamplePrint($validated);
    $exitCode = $validated->sucesso() ? 0 : 1;
} catch (Throwable $error) {
    acbrExampleError($error);
    $exitCode = 1;
} finally {
    $emitter?->fechar();
}
exit($exitCode);
