<?php
declare(strict_types=1);
// No HTTP, database, process mutation, or environment-value output.
if (($argv[1] ?? '') !== '--preflight') {
    fwrite(STDERR, "DENIED: --preflight required\n");
    exit(2);
}
$targets = [
    'A' => ['pid' => 13109, 'port' => 18105,
        'root' => '/private/tmp/zhct-http-ai-macos.zjaU8h',
        'source' => '/Users/wiscourper/Documents/workspace/local/dm8-full-acceptance.fF5yTy/baseline-a-ai-api-V4.0.40',
        'db_sha' => 'e7402b1ad50fcf4205326d93dc22e4f491c5052c60fcbe36214cd4e07b55343c'],
    'B' => ['pid' => 13127, 'port' => 18101,
        'root' => '/private/tmp/zhct-http-ai-macos.x2CCZX',
        'source' => '/Users/wiscourper/Documents/workspace/local/dm8-full-acceptance.fF5yTy/ai_api',
        'db_sha' => '8c46a6d9cd277f2950818d09162f639a62f135a5eb6553e6c61ce2c19167fd02'],
];
$local = parse_ini_file('/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api/.env.local', true, INI_SCANNER_RAW);
if (!is_array($local) || !isset($local['DATABASE'], $local['DATABASE_ZHCT'])) {
    throw new RuntimeException('local config unavailable');
}
$result = [];
foreach ($targets as $lane => $spec) {
    $root = $spec['root'];
    $pid = $spec['pid'];
    $port = $spec['port'];
    $ps = (string)shell_exec('/bin/ps eww -p ' . $pid . ' -o command=');
    $owners = trim((string)shell_exec('/usr/sbin/lsof -nP -t -iTCP:' . $port . ' -sTCP:LISTEN 2>/dev/null'));
    $has = static function (string $key, string $value) use ($ps): bool {
        if ($value === '' || preg_match('/\s/', $value)) return false;
        return preg_match('/(?:^|\s)' . preg_quote($key . '=' . $value, '/') . '(?=\s|$)/', $ps) === 1;
    };
    $configMatches = true;
    foreach (['DATABASE' => 'POC_AI_', 'DATABASE_ZHCT' => 'POC_'] as $section => $prefix) {
        foreach (['HOSTNAME' => 'HOST', 'HOSTPORT' => 'PORT', 'DATABASE' => 'SCHEMA',
            'USERNAME' => 'USER', 'PASSWORD' => 'PASSWORD'] as $from => $to) {
            $configMatches = $configMatches && $has($prefix . $to, (string)($local[$section][$from] ?? ''));
        }
    }
    $checks = [
        'exact_listener_owner' => $owners === (string)$pid,
        'fixed_php_docroot' => strpos($ps, '-S 127.0.0.1:' . $port) !== false
            && (strpos($ps, $root . '/public') !== false
                || strpos($ps, str_replace('/private/tmp/', '/tmp/', $root) . '/public') !== false),
        'single_worker' => strpos($ps, 'PHP_CLI_SERVER_WORKERS=') === false,
        'mysql_dialect' => $has('POC_DIALECT', 'mysql'),
        'external_stubs' => $has('POC_EXTERNAL_STUBS', '1'),
        'target_root' => $has('POC_TARGET_ROOT', $root)
            || $has('POC_TARGET_ROOT', str_replace('/private/tmp/', '/tmp/', $root)),
        'both_code_local_development_connections' => $configMatches,
        'root_private' => is_dir($root) && (fileperms($root) & 0777) === 0700,
        'actual_A_or_B_source' => realpath($root . '/app/api/controller/Bank.php')
            === realpath($spec['source'] . '/app/api/controller/Bank.php'),
        'pinned_db_config' => hash_file('sha256', $root . '/config/database.php') === $spec['db_sha'],
        'pinned_file_cache' => hash_file('sha256', $root . '/config/cache.php')
            === 'ccf1c56eb4178f3eaad8775e26a27742b2cacf662b46fb058cbb91d23783b8c6',
        'pinned_stubs' => hash_file('sha256', $root . '/external_stubs.php')
            === 'ed0ea9f23c70e504cf5331b7a95fe2a9fd6704beabf254a474efbe8ecb4d59a0',
    ];
    $result[$lane] = ['pid' => $pid, 'port' => $port,
        'checks' => $checks, 'pass' => !in_array(false, $checks, true)];
}
echo json_encode(['status' => 'read-only-runtime-identity', 'lanes' => $result], JSON_UNESCAPED_SLASHES), PHP_EOL;
exit($result['A']['pass'] && $result['B']['pass'] ? 0 : 3);
