<?php
declare(strict_types=1);

// Independent process: prove only this run's synthetic user/cart/cache key are gone.
$journal = (string)getenv('POC_PRIVATE_JOURNAL');
$root = (string)getenv('POC_TARGET_ROOT');
$dialect = (string)getenv('POC_DIALECT');
if ($journal === '' || !is_file($journal) || $root === ''
    || !in_array($dialect, ['mysql', 'dm'], true)) {
    throw new RuntimeException('Private journal and isolated runtime required');
}
$entry = json_decode((string)file_get_contents($journal), true);
if (!is_array($entry) || ($entry['stage'] ?? '') !== 'cleaned-awaiting-independent-zero'
    || ($entry['dialect'] ?? '') !== $dialect
    || !preg_match('/^CDXMCDEEP[0-9A-F]{10}$/', (string)($entry['marker'] ?? ''))
    || (int)($entry['user_id'] ?? 0) <= 0 || (int)($entry['cart_id'] ?? 0) <= 0) {
    throw new RuntimeException('Journal is not eligible for final zero verification');
}
if ($dialect === 'mysql') {
    $local = parse_ini_file((string)getenv('POC_MYSQL_LOCAL_ENV'), true, INI_SCANNER_RAW);
    if (!is_array($local) || !isset($local['DATABASE'])) {
        throw new RuntimeException('Development .env.local required');
    }
    foreach (['HOSTNAME' => 'HOST', 'HOSTPORT' => 'PORT', 'DATABASE' => 'SCHEMA',
        'USERNAME' => 'USER', 'PASSWORD' => 'PASSWORD'] as $source => $target) {
        putenv('POC_AI_' . $target . '=' . (string)$local['DATABASE'][$source]);
    }
}
foreach (['POC_AI_HOST', 'POC_AI_PORT', 'POC_AI_SCHEMA', 'POC_AI_USER',
    'POC_AI_PASSWORD'] as $name) {
    if (getenv($name) === false) throw new RuntimeException('AI database environment missing');
}
define('TP_ENV', 'poc');
define('BUSINESS', 'aizhct');
define('ENTERPRISE_NO', '10001');
require $root . '/vendor/autoload.php';
(new \think\App($root))->setEnvName('poc')->initialize();
$dsn = $dialect === 'dm'
    ? 'dm:host=' . getenv('POC_AI_HOST') . ';port=' . getenv('POC_AI_PORT')
        . ';schema=' . getenv('POC_AI_SCHEMA')
    : 'mysql:host=' . getenv('POC_AI_HOST') . ';port=' . getenv('POC_AI_PORT')
        . ';dbname=' . getenv('POC_AI_SCHEMA') . ';charset=utf8mb4';
$pdo = new PDO($dsn, getenv('POC_AI_USER'), getenv('POC_AI_PASSWORD'),
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$u = $dialect === 'dm' ? 'YOSHOP_USER' : 'yoshop_user';
$c = $dialect === 'dm' ? 'YOSHOP_MEAL_CART' : 'yoshop_meal_cart';
$count = static function (string $sql, array $params) use ($pdo): int {
    $q = $pdo->prepare($sql);
    $q->execute($params);
    return (int)$q->fetchColumn();
};
$userId = (int)$entry['user_id'];
$cartId = (int)$entry['cart_id'];
$marker = (string)$entry['marker'];
$token = (string)$entry['token'];
$userCount = $count("SELECT COUNT(*) FROM $u WHERE USER_ID=? OR NICK_NAME=?",
    [$userId, $marker]);
$cartCount = $count("SELECT COUNT(*) FROM $c WHERE ID=? OR USER_ID=?",
    [$cartId, $userId]);
$cacheAbsent = \think\facade\Cache::get($token, null) === null;
if ($userCount !== 0 || $cartCount !== 0 || !$cacheAbsent) {
    throw new RuntimeException('Independent zero readback failed');
}
unlink($journal);
echo json_encode(['stage' => 'independent-zero', 'dialect' => $dialect,
    'user_rows' => 0, 'cart_rows' => 0, 'cache_key_absent' => true,
    'journal_removed' => !is_file($journal)], JSON_UNESCAPED_UNICODE) . PHP_EOL;
