<?php
declare(strict_types=1);

// Independent second-process zero readback of only this run's random File-cache token.
if (getenv('CDX_READ8_TOKEN_ZERO') !== 'APPROVED_INDEPENDENT_ZERO_V1') {
    echo json_encode(['status' => 'default_deny', 'db' => 0, 'http' => 0]), PHP_EOL;
    exit(78);
}
$target = (string)getenv('CDX_READ8_TARGET');
$journal = (string)getenv('CDX_READ8_JOURNAL');
$sha = (string)getenv('CDX_READ8_SHA');
if (!in_array($target, ['A', 'B', 'C'], true)
    || strlen($sha) !== 64 || !hash_equals($sha, (string)hash_file('sha256', __FILE__))) {
    throw new RuntimeException('Target or script SHA mismatch');
}
$root = ['A' => '/private/tmp/zhct-http-ai-macos.zjaU8h',
    'B' => '/private/tmp/zhct-http-ai-macos.x2CCZX',
    'C' => '/tmp/zhct-ai-http-20260929.3XDj3w'][$target];
$journalReal = realpath($journal);
$dir = $journalReal === false ? false : realpath(dirname($journalReal));
$tempRoot = realpath(sys_get_temp_dir());
if (!is_string($journalReal) || !is_string($dir) || !is_string($tempRoot)
    || basename($journalReal) !== 'token.json'
    || strpos(basename($dir), 'cdx-ai-read8-') !== 0
    || dirname($dir) !== $tempRoot
    || (((int)fileperms($dir) & 0077) !== 0)
    || (((int)fileperms($journalReal) & 0077) !== 0)) {
    throw new RuntimeException('Private token journal boundary mismatch');
}
$manifest = json_decode((string)file_get_contents($journalReal), true);
if (!is_array($manifest) || ($manifest['target'] ?? null) !== $target
    || ($manifest['root'] ?? null) !== $root
    || !preg_match('/^CDXREAD8T[A-F0-9]{36}$/', (string)($manifest['token'] ?? ''))
    || (int)($manifest['expires_at'] ?? 0) - (int)($manifest['created_at'] ?? 0) !== 300) {
    throw new RuntimeException('Private token journal content mismatch');
}
if (realpath($root . '/runtime/cache') !== $root . '/runtime/cache'
    || !hash_equals('ccf1c56eb4178f3eaad8775e26a27742b2cacf662b46fb058cbb91d23783b8c6',
        (string)hash_file('sha256', $root . '/config/cache.php'))) {
    throw new RuntimeException('File cache configuration changed');
}
define('TP_ENV', 'poc');
define('BUSINESS', 'aizhct');
define('ENTERPRISE_NO', '10001');
require $root . '/vendor/autoload.php';
(new \think\App($root))->setEnvName('poc')->initialize();
if (strtolower((string)\think\facade\Config::get('cache.default')) !== 'file'
    || realpath((string)\think\facade\Config::get('cache.stores.file.path'))
        !== $root . '/runtime/cache') {
    throw new RuntimeException('Effective File cache changed');
}
$absent = !\think\facade\Cache::has($manifest['token']);
if (!$absent) {
    echo json_encode(['status' => 'token_present', 'target' => $target,
        'role' => $manifest['role'] ?? null]), PHP_EOL;
    exit(3);
}
$rowsExactZero = null;
if (($manifest['role'] ?? null) === 'health_schedule') {
    $marker = (string)($manifest['marker'] ?? '');
    $ids = $manifest['ids'] ?? null;
    if (!preg_match('/^CDXREAD8H[A-F0-9]{10}$/', $marker) || !is_array($ids)) {
        throw new RuntimeException('Health fixture journal marker invalid');
    }
    putenv('CDX_READ2_TARGET=' . $target);
    putenv('CDX_READ2_SCHEMA_PREFLIGHT=1');
    require $target === 'C'
        ? '/tmp/zhct-ai-read2-VgKO4CDY/read2_schema_preflight.php'
        : __DIR__ . '/../parallel-ai-next-read-safe4/read2_schema_preflight.php';
    $table = static function (string $name) use ($dialect): string {
        return $dialect === 'dm' ? 'YOSHOP_' . $name : 'yoshop_' . strtolower($name);
    };
    $checks = [
        [$table('USER'), 'NICK_NAME', $marker],
        [$table('STAFF'), 'NAME', $marker],
        [$table('HEALTH_SUGGESTION'), 'K1', $marker],
    ];
    if (isset($ids['user'])) $checks[] = [$table('USER_WEIGHT_STATUS'), 'USER_ID', (int)$ids['user']];
    if (isset($ids['staff'])) $checks[] = [$table('HEALTH_SUGGESTION_WORK'), 'STAFF_ID', (int)$ids['staff']];
    $rowsExactZero = true;
    foreach ($checks as [$name, $column, $value]) {
        $stmt = $ai->prepare('SELECT COUNT(*) FROM ' . $name
            . ' WHERE ' . $column . '=? AND STORE_ID=10001');
        $stmt->execute([$value]);
        $rowsExactZero = $rowsExactZero && (int)$stmt->fetchColumn() === 0;
    }
    if (!$rowsExactZero) {
        echo json_encode(['status' => 'health_fixture_rows_remain', 'target' => $target]), PHP_EOL;
        exit(4);
    }
}
if (!unlink($journalReal) || !rmdir($dir)) {
    throw new RuntimeException('Private token journal cleanup failed');
}
echo json_encode(['status' => 'independent_token_zero', 'target' => $target,
    'role' => $manifest['role'] ?? null, 'cache_key_absent' => true,
    'private_journal_removed' => true, 'health_rows_exact_zero' => $rowsExactZero,
    'http' => 0]), PHP_EOL;
