<?php
declare(strict_types=1);

// Copie examples/ para a raiz de um consumidor Composer, ou informe o autoload.
$autoload = getenv('ACBR_PHP_AUTOLOAD');
if ($autoload === false || $autoload === '') {
    $autoload = dirname(__DIR__) . '/vendor/autoload.php';
}
if (str_contains($autoload, '://') || !is_file($autoload)) {
    fwrite(STDERR, "Configure ACBR_PHP_AUTOLOAD para um autoload local instalado.\n");
    exit(2);
}
require_once $autoload;

function acbrExamplePrint(array|JsonSerializable $value): void
{
    echo json_encode($value, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR), PHP_EOL;
}

function acbrExampleError(Throwable $error): void
{
    if ($error instanceof Acbr\AcbrException || $error instanceof Acbr\Model\ValidationException) {
        acbrExamplePrint($error);
    } elseif ($error instanceof Acbr\Model\FieldHelpException) {
        acbrExamplePrint(['codigo' => $error->codigo, 'candidates' => $error->candidates]);
    } else {
        // Não imprimir traces/argumentos, XML, caminhos de segredo ou mensagem livre.
        acbrExamplePrint(['codigo' => 'EXEMPLO_FALHOU', 'mensagem' => 'Confira os pre-requisitos e a configuracao local.']);
    }
}

function acbrExampleDocument(): Acbr\Document
{
    $json = file_get_contents(__DIR__ . '/documento-sintetico.json');
    if ($json === false) {
        throw new RuntimeException('Fixture sintetica ausente.');
    }
    $document = Acbr\Document::fromJson($json);
    $data = $document->toArray();
    if (($data['Ide']['tpAmb'] ?? null) !== 'taHomologacao') {
        throw new RuntimeException('Os exemplos exigem HOMOLOGACAO.');
    }
    return $document;
}
