<?php

function cli_error(string $message): void
{
    $stderr = fopen('php://stderr', 'w');
    if ($stderr !== false) {
        fwrite($stderr, $message);
        fclose($stderr);
        return;
    }
    echo $message;
}

if ($argc !== 3) {
    cli_error("Usage: {$argv[0]} <input.phpast> <output.php>\n");
    exit(2);
}

$encodedAst = @file_get_contents($argv[1]);
if ($encodedAst === false) {
    cli_error("Could not read input file: {$argv[1]}\n");
    exit(1);
}

try {
    $bundle = PhpSerializedBundle::unpack($encodedAst);
    $ast = is_array($bundle) && ($bundle['format'] ?? null) === 'php-parser-ast-v0'
        ? ($bundle['ast'] ?? [])
        : $bundle;
    $php = PhpAstProcessor::ast2php($ast);
} catch (Throwable $error) {
    cli_error($error->getMessage() . "\n");
    exit(1);
}

if (file_put_contents($argv[2], $php) === false) {
    cli_error("Could not write output file: {$argv[2]}\n");
    exit(1);
}

echo "Wrote PHP to {$argv[2]}\n";
