<?php
declare(strict_types=1);
// Save in the root of the downloaded project, next to composer.json.
// composer install
// php order-example.php
// php order-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 (
  'customerEmail' => 'buyer@example.test',
  'delivery' => 'pickup',
  'items' => 
  array (
    0 => 
    array (
      'sku' => 'KB-01',
      'quantity' => 2,
      'price' => 1500,
    ),
    1 => 
    array (
      'sku' => 'MS-02',
      'quantity' => 1,
      'price' => 900,
    ),
  ),
);
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 !== 'order') { throw new RuntimeException('Scenario mismatch.'); }
            $envelope = $input;
        } else {
            $envelope = (object) ['scenario' => 'order', '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 КБ с данными сценария order.\n"); exit(2);
    }
} else {
    $result = Engine::validate('order', $data);
}
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR), PHP_EOL;
exit($result['valid'] ? 0 : 1);
