<?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.php> <output.phpast>\n");
    exit(2);
}

$inputFile = $argv[1];
$outputFile = $argv[2];

$code = @file_get_contents($inputFile);
if ($code === false) {
    cli_error("Could not read input file: {$inputFile}\n");
    exit(1);
}

try {
    $ast = PhpAstProcessor::phpSource2ast($code);
    $sourceFile = realpath($inputFile);
    $encodedAst = PhpSerializedBundle::pack([
        'format' => 'php-parser-ast-v0',
        'phpSourceFile' => $sourceFile !== false ? $sourceFile : $inputFile,
        'ast' => $ast,
    ]);
} catch (Throwable $error) {
    cli_error($error->getMessage() . "\n");
    exit(1);
}

if (file_put_contents($outputFile, $encodedAst) === false) {
    cli_error("Could not write output file: {$outputFile}\n");
    exit(1);
}

echo "Wrote AST to {$outputFile}\n";
