<?php

declare(strict_types=1);

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

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

if (!is_string($input) || trim($input) === '') {
    fwrite(STDERR, "Usage: php compile-style-definition.php --input=/path/to/style.jsonm [--output=/path/to/app/assets/runtime/css/runtime-token-overrides.css]\n");
    exit(1);
}

try {
    $definition = StyleDefinitionRuntime::loadJson($input);
    $tokenMap = StyleDefinitionRuntime::loadTokenMap();
    $compiled = StyleDefinitionRuntime::compileDefinition($definition, $tokenMap);

    if (is_string($output) && trim($output) !== '') {
        StyleDefinitionRuntime::writeFile($output, $compiled);
        fwrite(STDOUT, "Compiled CSS written to {$output}\n");
    } else {
        fwrite(STDOUT, $compiled);
    }
    exit(0);
} catch (Throwable $e) {
    fwrite(STDERR, $e->getMessage() . "\n");
    exit(1);
}
