<?php

function valair_typing_previous_result_text(object $ir): ?string
{
    $array = ValaIrOptimizerSupport::toDebugArray($ir);
    $matches = [];
    $walk = static function (mixed $node) use (&$walk, &$matches): void {
        if (!is_array($node)) {
            return;
        }
        if (($node['kind'] ?? null) === 'Comment') {
            $text = (string) ($node['text'] ?? $node['value'] ?? '');
            if (preg_match('#phpefc optimizer typing-zval2static result: ([0-9]+/[0-9]+ zvals left)#', $text, $m)) {
                $matches[] = $m[1];
            }
        }
        foreach ($node as $value) {
            $walk($value);
        }
    };
    $walk($array);
    return $matches === [] ? null : end($matches);
}

function valair_optimize_typing_zval2static(object $valaIr, array $options = []): object
{
    $suppressWarning = isset($options['--suppress-warning']);
    $previousResultText = valair_typing_previous_result_text($valaIr);
    $optimizer = new ValaIrTypingZval2StaticOptimizer();
    $optimized = $optimizer->optimize($valaIr);

    if (!$suppressWarning && $optimizer->hasRemainingDynamicZvals()) {
        $resultText = $optimizer->getLastResultText();
        if ($previousResultText !== null) {
            $resultText .= '; first pass ' . $previousResultText;
        }
        ValaIrOptimizerSupport::cliRedWarning("WARNING: PERFORMANCE NOT OPTIMIZED THROUGH DYNAMIC ZVALS (" . $resultText . ")\n");
    }

    return $optimized;
}

ValaIrOptimizerSupport::runFixedCli(
    $argv,
    $argc,
    "typing-zval2static",
    "valair_optimize_typing_zval2static",
    ["--suppress-warning"],
);
