<?php

declare(strict_types=1);

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

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

try {
    $tokenMap = StyleDefinitionRuntime::loadTokenMap();
    $definition = StyleDefinitionRuntime::exportCurrentDefinition(
        $tokenMap,
        is_string($id) && trim($id) !== '' ? $id : null,
        is_string($name) && trim($name) !== '' ? $name : null
    );
    $json = StyleDefinitionRuntime::jsonEncodePretty($definition);

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