<?php
declare(strict_types=1);

$stage = 'default_deny';
if (!hash_equals('CDX_CAT8F_READBACK_20261002_V1',
    (string)getenv('CDX_CAT8F_APPROVAL'))) {
    echo json_encode(['status' => 'default_deny', 'database_connected' => false,
        'cache_accessed' => false, 'business_http_sent' => false,
        'dml_sent' => false]), PHP_EOL;
    exit(78);
}
$redactedError = static function (Throwable $error) use (&$stage): void {
    echo json_encode(['status' => 'redacted_error', 'stage' => $stage,
        'class' => get_class($error), 'writes' => false]), PHP_EOL;
    exit(2);
};
set_exception_handler($redactedError);
set_error_handler(static function (int $severity): bool {
    if (!(error_reporting() & $severity)) return false;
    throw new ErrorException('redacted_warning', 0, $severity);
});
$stage = 'source_review';
require __DIR__ . '/common.php';
cat8f_approved('CDX_CAT8F_READBACK_20261002_V1', __FILE__);
$data = cat8f_manifest();
$target = (string)getenv('CDX_CAT8F_TARGET');
if ($target !== $data['target']) throw new RuntimeException('Target mismatch');
$stage = 'isolated_runtime';
try {
    $ctx = cat8_context($target);
} catch (Throwable $error) {
    $redactedError($error);
}
set_exception_handler($redactedError);
if ($ctx['schema'] !== $data['schema']) throw new RuntimeException('Schema mismatch');
/** @var PDO $db */
$db = $ctx['pdo'];
$rows = cat8f_operator($db, $data['user_name']);
$cache = cat8f_cache_state($data);
$userId = count($rows) === 1 ? (int)$rows[0]['store_user_id']
    : (int)($data['store_user_id'] ?? 0);
$refs = $userId > 0 ? cat8f_refs($db, $userId) : [];
$ready = count($rows) === 1 && cat8f_owned($rows[0], $data)
    && (int)$data['store_user_id'] === $userId
    && array_sum($refs) === 0
    && ($data['status'] ?? null) === 'ready'
    && ($cache['live'] ?? false) && ($cache['ttl_valid'] ?? false)
    && ($cache['session'] ?? null) === cat8f_session($data, $userId)
    && (int)$data['expires_at'] > time() + 20;
$zero = count($rows) === 0 && !$cache['exists']
    && array_sum($refs) === 0 && ($data['status'] ?? null) === 'cleaned';
$status = $ready ? 'ready_independent_readback'
    : ($zero ? 'independent_zero_readback' : 'partial_or_ambiguous_manual_review');
if (!$ready && !$zero && count($rows) === 1
    && cat8f_owned($rows[0], $data) && array_sum($refs) === 0
    && (!$cache['exists'] || isset($cache['expires_at']))
    && !($cache['live'] ?? false)) {
    $status = 'owned_account_without_live_session_cleanup_candidate';
}
echo json_encode(['status' => $status, 'target' => $target,
    'synthetic_account_rows' => count($rows),
    'short_session_valid' => $ready,
    'cache_file_absent' => !$cache['exists'],
    'known_relation_counts' => $refs,
    'journal_phase' => (string)($data['phase'] ?? ''),
    'writes' => false, 'business_http_sent' => false]), PHP_EOL;
if (!$ready && !$zero) exit(3);
