<?php

if (!defined('WD')) {
    define('WD', dirname(__DIR__, 2));
}

function app_path(string $relative = ''): string
{
    if ($relative === '') {
        return WD;
    }

    return WD . DIRECTORY_SEPARATOR . ltrim(str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $relative), DIRECTORY_SEPARATOR);
}

function app_require(string $relative): void
{
    require_once app_path($relative);
}

function integration_enabled(): bool
{
    return getenv('RUN_INTEGRATION_TESTS') === '1';
}

function run_legacy_script(string $relativeScriptPath): array
{
    $script = app_path($relativeScriptPath);
    if (!is_file($script)) {
        return ['exitCode' => 1, 'output' => 'Missing legacy script: ' . $script];
    }

    $phpBinary = PHP_BINARY ?: 'php';
    $command = escapeshellarg($phpBinary) . ' ' . escapeshellarg($script) . ' 2>&1';
    $outputLines = [];
    $exitCode = 0;
    exec($command, $outputLines, $exitCode);

    return ['exitCode' => $exitCode, 'output' => implode(PHP_EOL, $outputLines)];
}
