<?php

/**
 * Run the fixed fastpath-runtime optimizer CLI.
 *
 * @param array $argv Raw command-line arguments.
 * @param int $argc Argument count.
 * @return int Process exit code.
 */
function valair_optimize_fastpath_runtime_cli(array $argv, int $argc): int
{
    $positionals = [];
    $externalValairFiles = [];
    for ($i = 1; $i < $argc; $i++) {
        if ($argv[$i] === "--external-valair") {
            $i++;
            if ($i >= $argc) {
                ValaIrOptimizerSupport::cliError("Missing value for --external-valair\n");
                return 2;
            }
            $externalValairFiles[] = $argv[$i];
            continue;
        }
        if (str_starts_with($argv[$i], "--")) {
            ValaIrOptimizerSupport::cliError("Unknown option: {$argv[$i]}\n");
            return 2;
        }
        $positionals[] = $argv[$i];
    }

    if (count($positionals) !== 2) {
        ValaIrOptimizerSupport::usage($argv[0], "fastpath-runtime", ["--external-valair <file>"]);
        return 2;
    }

    [$inputFile, $outputFile] = $positionals;
    $serializedIr = @file_get_contents($inputFile);
    if ($serializedIr === false) {
        ValaIrOptimizerSupport::cliError("Could not read input file: {$inputFile}\n");
        return 1;
    }

    try {
        $ir = PhpSerializedBundle::unpack($serializedIr);
        $externalValaIrs = [];
        foreach ($externalValairFiles as $externalValairFile) {
            $serializedExternalIr = @file_get_contents($externalValairFile);
            if ($serializedExternalIr === false) {
                throw new RuntimeException("Could not read external Vala IR file: {$externalValairFile}");
            }
            $externalValaIrs[] = PhpSerializedBundle::unpack($serializedExternalIr);
        }

        $optimizer = new ValaIrFastPathRuntimeOptimizer(null, $externalValaIrs);
        $optimized = $optimizer->optimize($ir);

        if ($optimizer->hasRemainingRuntimeDispatchCalls()) {
            ValaIrOptimizerSupport::cliRedWarning("WARNING: PERFORMANCE NOT OPTIMIZED THROUGH RUNTIME DISPATCH (" . $optimizer->getLastResultText() . ")\n");
        }

        $serializedOptimized = PhpSerializedBundle::pack($optimized);
    } catch (Throwable $error) {
        ValaIrOptimizerSupport::cliError($error->getMessage() . "\n");
        return 1;
    }

    if (file_put_contents($outputFile, $serializedOptimized) === false) {
        ValaIrOptimizerSupport::cliError("Could not write output file: {$outputFile}\n");
        return 1;
    }

    echo "Wrote optimized Vala IR (fastpath-runtime) to {$outputFile}\n";
    return 0;
}

exit(valair_optimize_fastpath_runtime_cli($argv, $argc));
