<?php
declare(strict_types=1);
// Save in the root of the downloaded project, next to composer.json.
// composer install
// php import-example.php
// php import-example.php request.json
// Actual Symfony constraints live in src/Rules.php; Engine serializes only path/message/code.
require __DIR__ . '/vendor/autoload.php';
use Aen\ValidatorWorkshop\Engine;
use Aen\ValidatorWorkshop\HttpApi;

$data = array (
  'rows' => 
  array (
    0 => 
    array (
      'name' => 'Анна',
      'email' => 'anna@example.test',
      'age' => 28,
    ),
    1 => 
    array (
      'name' => 'Борис',
      'email' => 'boris@example.test',
      'age' => 35,
    ),
  ),
);
if (isset($argv[1])) {
    try {
        $raw = @file_get_contents($argv[1], false, null, 0, HttpApi::MAX_BYTES + 1);
        if ($raw === false || strlen($raw) > HttpApi::MAX_BYTES) { throw new RuntimeException('Invalid file size.'); }
        $input = json_decode($raw, false, 16, JSON_THROW_ON_ERROR);
        if (!$input instanceof stdClass) { throw new RuntimeException('Object required.'); }
        if (property_exists($input, 'scenario')) {
            if ($input->scenario !== 'import') { throw new RuntimeException('Scenario mismatch.'); }
            $envelope = $input;
        } else {
            $envelope = (object) ['scenario' => 'import', 'data' => $input];
        }
        $response = HttpApi::handle('POST', 'application/json', json_encode($envelope, JSON_THROW_ON_ERROR));
        $result = $response['body'];
        if (!in_array($response['status'], [200, 422], true)) {
            echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR), PHP_EOL;
            exit(2);
        }
    } catch (Throwable) {
        fwrite(STDERR, "Нужен JSON-объект до 32 КБ с данными сценария import.\n"); exit(2);
    }
} else {
    $result = Engine::validate('import', $data);
}
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR), PHP_EOL;
exit($result['valid'] ? 0 : 1);
