<?php

declare(strict_types=1);

require_once __DIR__ . '/runtime/autoload.php';

$options = getopt('', ['input:']);
$input = $options['input'] ?? null;

if (!is_string($input) || trim($input) === '') {
    fwrite(STDERR, "Usage: php validate-style-definition.php --input=/absolute/or/relative/path.jsonm\n");
    exit(1);
}

try {
    $definition = StyleDefinitionRuntime::loadJson($input);
    $tokenMap = StyleDefinitionRuntime::loadTokenMap();
    $errors = StyleDefinitionRuntime::validateDefinition($definition, $tokenMap);

    if ($errors !== []) {
        fwrite(STDERR, "Validation failed:\n");
        foreach ($errors as $error) {
            fwrite(STDERR, "- {$error}\n");
        }
        exit(1);
    }

    foreach (StyleDefinitionRuntime::migrationWarnings($definition) as $warning) {
        fwrite(STDERR, "Migration warning: {$warning}\n");
    }

    fwrite(STDOUT, "OK: style definition is valid.\n");
    exit(0);
} catch (Throwable $e) {
    fwrite(STDERR, $e->getMessage() . "\n");
    exit(1);
}
