<?php
declare(strict_types=1);

// DEFAULT DENY. This only tests the no-staff user nickname branch, not the full profile chain.
$phase = (string)($argv[1] ?? '');
$lane = (string)($argv[2] ?? '');
$marker = (string)($argv[3] ?? '');
if (!in_array($phase, ['--preflight', '--run', '--audit', '--recover-probe'], true)
    || !in_array($lane, ['B', 'C'], true)
    || !preg_match('/^CDXPERSONAL[0-9A-F]{8}$/', $marker)) {
    fwrite(STDERR, "DENIED: exact phase/lane/marker required\n");
    exit(78);
}
if (in_array($phase, ['--run', '--audit'], true)) {
    $reviewed = (string)getenv('CDX_PERSONAL_REVIEWED_SHA256');
    if ((string)getenv('CDX_PERSONAL_APPROVAL') !== 'OWNED_PERSONAL_NO_STAFF_V1'
        || !preg_match('/^[a-f0-9]{64}$/', $reviewed)
        || ($lane === 'B' && hash_file('sha256', __FILE__) !== $reviewed)
        || ($lane === 'C' && (string)getenv('CDX_PERSONAL_SOURCE_CHECKED') !== '1')) {
        fwrite(STDERR, "DENIED: reviewed SHA/write-HTTP gate required\n");
        exit(78);
    }
}
$stage = 'start';
set_exception_handler(static function (Throwable $e) use (&$stage): void {
    fwrite(STDERR, 'PERSONAL_STOP stage=' . $stage
        . ' class=' . get_class($e) . "\n");
    exit(3);
});
$root = $lane === 'B' ? '/private/tmp/zhct-http-ai-macos.x2CCZX'
    : '/tmp/zhct-ai-http-20260929.3XDj3w';
$pid = $lane === 'B' ? 13127 : 53772;
$port = $lane === 'B' ? 18101 : 18102;
$base = 'http://127.0.0.1:' . $port;
if ($lane === 'B') {
    $cfg = parse_ini_file('/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api/.env.local', true, INI_SCANNER_RAW)['DATABASE'] ?? null;
    $ps = (string)shell_exec('/bin/ps eww -p ' . $pid . ' -o command=');
    $owner = trim((string)shell_exec('/usr/sbin/lsof -nP -t -iTCP:' . $port . ' -sTCP:LISTEN 2>/dev/null'));
    if (!is_array($cfg) || strtolower((string)($cfg['TYPE'] ?? '')) !== 'mysql'
        || (string)($cfg['HOSTPORT'] ?? '') !== '3306' || $owner !== (string)$pid
        || strpos($ps, 'POC_DIALECT=mysql') === false
        || strpos($ps, 'POC_EXTERNAL_STUBS=1') === false) {
        throw new RuntimeException('B worker/config drift');
    }
    foreach (['HOSTNAME' => 'HOST', 'HOSTPORT' => 'PORT', 'DATABASE' => 'SCHEMA',
              'USERNAME' => 'USER', 'PASSWORD' => 'PASSWORD'] as $from => $to) {
        $v = (string)($cfg[$from] ?? '');
        if ($v === '' || strpos($ps, 'POC_AI_' . $to . '=' . $v) === false) {
            throw new RuntimeException('B worker differs from code local config');
        }
    }
    $connect = static function () use ($cfg): PDO {
        return new PDO('mysql:host=' . $cfg['HOSTNAME'] . ';port=' . $cfg['HOSTPORT']
            . ';dbname=' . $cfg['DATABASE'] . ';charset=' . $cfg['CHARSET'],
            $cfg['USERNAME'], $cfg['PASSWORD'],
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_LOWER]);
    };
    $envName = 'local';
} else {
    $env = [];
    foreach (explode("\0", (string)file_get_contents('/proc/' . $pid . '/environ')) as $item) {
        $pair = explode('=', $item, 2);
        if (count($pair) === 2) $env[$pair[0]] = $pair[1];
    }
    if (($env['POC_TARGET_ROOT'] ?? '') !== $root
        || ($env['POC_BASE_URL'] ?? '') !== $base
        || ($env['POC_DIALECT'] ?? '') !== 'dm'
        || ($env['POC_EXTERNAL_STUBS'] ?? '') !== '1'
        || ($env['POC_AI_HOST'] ?? '') !== '127.0.0.1'
        || ($env['POC_AI_PORT'] ?? '') !== '5238'
        || ($env['POC_AI_SCHEMA'] ?? '') !== 'AIZHCT_APP'
        || ($env['POC_AI_USER'] ?? '') !== 'AIZHCT_APP'
        || !in_array('dm', PDO::getAvailableDrivers(), true)) {
        throw new RuntimeException('C worker/config drift');
    }
    $connect = static function () use ($env): PDO {
        $db = new PDO('dm:host=127.0.0.1;port=5238;schema=AIZHCT_APP',
            $env['POC_AI_USER'], $env['POC_AI_PASSWORD'],
            [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_LOWER]);
        if ($db->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn() !== 'AIZHCT_APP') {
            throw new RuntimeException('C schema drift');
        }
        return $db;
    };
    $envName = 'poc';
}
$loader = require $root . '/vendor/autoload.php';
if (!is_object($loader) || !method_exists($loader, 'findFile')) {
    throw new RuntimeException('Composer loader absent');
}
foreach ([
    'app\\api\\controller\\User' => '7834cf8b84369382ea5d6ce0eed946c6ebe3224d7f7fcb53085c14a7cbb1f471',
    'app\\api\\model\\User' => 'cd2855df8b0ab7869451e5189c6c28b9d10d1ce568664bd0427f2bfea2c30699',
    'app\\api\\service\\User' => '1fd7986c12b23a86f00721b948832b48fdd75da378f42982a1ea355fe7d6a8e3',
    'app\\common\\model\\User' => '79cf67679f66ac92667d6d668128ec5fd4484fd42574aae93fdff80af9c5e897',
    'app\\api\\model\\Store' => 'b208604f444041d6664aca6712f1ff05c7a9174be5341b20cb904d68d12ef21a',
    'app\\api\\model\\UserOauth' => '1b13be9aaeb83c7bb238a7654218ddae890c17a319fa2bd580fa51c8b0897f93',
] as $class => $sha) {
    $file = $loader->findFile($class);
    $real = is_string($file) ? realpath($file) : false;
    if (!is_string($real) || !is_file($real)
        || hash_file('sha256', $real) !== $sha) {
        throw new RuntimeException('Actual Composer user source drift');
    }
}
$db = $connect();
$userTable = $lane === 'B' ? 'yoshop_user' : 'YOSHOP_USER';
$staffTable = $lane === 'B' ? 'yoshop_staff' : 'YOSHOP_STAFF';
$count = static function (PDO $d, string $sql, array $args = []): int {
    $s = $d->prepare($sql);
    $s->execute($args);
    return (int)$s->fetchColumn();
};
$query = static function (PDO $d, string $sql, array $args = []): array {
    $s = $d->prepare($sql);
    $s->execute($args);
    return $s->fetchAll(PDO::FETCH_ASSOC);
};
$refSql = $lane === 'B'
    ? "SELECT TABLE_NAME,COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME LIKE 'yoshop_%' AND UPPER(COLUMN_NAME)='USER_ID' ORDER BY TABLE_NAME"
    : "SELECT TABLE_NAME,COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME LIKE 'YOSHOP_%' AND COLUMN_NAME='USER_ID' ORDER BY TABLE_NAME";
$refs = $query($db, $refSql);
if (count($refs) < 30 || count($refs) > 250) {
    throw new RuntimeException('User reference inventory unexpected');
}
foreach ($refs as $ref) {
    if (!preg_match('/^[A-Za-z_][A-Za-z0-9_]*$/', (string)$ref['table_name'])
        || strtoupper((string)$ref['column_name']) !== 'USER_ID') {
        throw new RuntimeException('Unsafe reference metadata');
    }
}
if ($lane === 'B') {
    $triggers = $count($db, "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TRIGGERS WHERE TRIGGER_SCHEMA=DATABASE() AND EVENT_OBJECT_TABLE IN ('yoshop_user','yoshop_staff')");
    $fks = $count($db, "SELECT COUNT(*) FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA=DATABASE() AND REFERENCED_TABLE_NAME IS NOT NULL AND (TABLE_NAME IN ('yoshop_user','yoshop_staff') OR REFERENCED_TABLE_NAME IN ('yoshop_user','yoshop_staff'))");
    $identity = $count($db, "SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='yoshop_user' AND COLUMN_NAME='user_id' AND EXTRA LIKE '%auto_increment%'") === 1;
} else {
    $triggers = $count($db, "SELECT COUNT(*) FROM USER_TRIGGERS WHERE TABLE_NAME IN ('YOSHOP_USER','YOSHOP_STAFF')");
    $fks = $count($db, "SELECT COUNT(*) FROM USER_CONSTRAINTS WHERE CONSTRAINT_TYPE='R' AND (TABLE_NAME IN ('YOSHOP_USER','YOSHOP_STAFF') OR R_CONSTRAINT_NAME IN (SELECT CONSTRAINT_NAME FROM USER_CONSTRAINTS WHERE TABLE_NAME IN ('YOSHOP_USER','YOSHOP_STAFF'))) ");
    $s = $db->prepare('CALL SP_TABLEDEF(?, ?)');
    $s->execute(['AIZHCT_APP', $userTable]);
    $ddl = $s->fetchColumn();
    if (is_resource($ddl)) $ddl = stream_get_contents($ddl);
    $identity = is_string($ddl)
        && preg_match('/"USER_ID"\s+[A-Z0-9_]+\s+(?:AUTO_INCREMENT|IDENTITY)/i', $ddl) === 1;
}
if ($triggers !== 0 || $fks !== 0 || !$identity) {
    throw new RuntimeException('User/staff schema side-effect gate drift');
}
$markerCount = $count($db, 'SELECT COUNT(*) FROM ' . $userTable
    . ' WHERE STORE_ID=10001 AND NICK_NAME=?', [$marker]);
$journalDir = sys_get_temp_dir() . '/cdx-personal-no-staff-'
    . strtolower($lane) . '-' . strtolower($marker);
$journalPath = $journalDir . '/journal.json';
$save = static function (array $j) use ($journalPath): void {
    $body = json_encode($j, JSON_UNESCAPED_SLASHES);
    $tmp = $journalPath . '.tmp';
    if (!is_string($body) || file_put_contents($tmp, $body, LOCK_EX) !== strlen($body)
        || !chmod($tmp, 0600) || !rename($tmp, $journalPath)) {
        throw new RuntimeException('Private journal write failed');
    }
};
$insert = 'INSERT INTO ' . $userTable
    . ' (STORE_ID,MOBILE,NICK_NAME,BALANCE,GIFT_BALANCE,IS_DELETE,CREATE_TIME)'
    . ' VALUES (10001,?,?,0,0,0,?)';
$db->prepare($insert);
if ($phase === '--preflight') {
    echo json_encode(['lane' => $lane, 'phase' => $phase,
        'marker_count' => $markerCount,
        'user_id_reference_columns' => count($refs),
        'identity' => true, 'triggers' => 0, 'foreign_keys' => 0,
        'insert_prepare_ready' => true,
        'journal_absent' => !file_exists($journalDir),
        'business_http' => 0, 'business_dml' => 0], JSON_UNESCAPED_SLASHES), "\n";
    exit($markerCount === 0 && !file_exists($journalDir) ? 0 : 3);
}
$journal = is_file($journalPath)
    ? json_decode((string)file_get_contents($journalPath), true) : null;
if (is_array($journal) && (($journal['lane'] ?? '') !== $lane
    || ($journal['marker'] ?? '') !== $marker)) {
    throw new RuntimeException('Exact journal identity drift');
}
if ($phase === '--recover-probe') {
    echo json_encode(['lane' => $lane, 'phase' => $phase,
        'journal_phase' => is_array($journal) ? ($journal['phase'] ?? 'invalid') : 'absent',
        'journal_id' => is_array($journal) ? ($journal['id'] ?? 0) : 0,
        'marker_count' => $markerCount,
        'business_http' => 0, 'business_dml' => 0], JSON_UNESCAPED_SLASHES), "\n";
    exit(0);
}
if ($phase === '--audit') {
    if (!is_array($journal) || (int)($journal['id'] ?? 0) <= 0
        || ($journal['phase'] ?? '') !== 'cleanup_committed') {
        throw new RuntimeException('Exact cleanup journal absent');
    }
    $verify = $connect();
    $id = (int)$journal['id'];
    if ($count($verify, 'SELECT COUNT(*) FROM ' . $userTable
            . ' WHERE USER_ID=?', [$id]) !== 0
        || $count($verify, 'SELECT COUNT(*) FROM ' . $staffTable
            . ' WHERE USER_ID=?', [$id]) !== 0
        || $count($verify, 'SELECT COUNT(*) FROM ' . $userTable
            . ' WHERE NICK_NAME=? AND STORE_ID=10001', [$marker]) !== 0) {
        throw new RuntimeException('Independent user/staff zero failed');
    }
    foreach ($refs as $ref) {
        if ($count($verify, 'SELECT COUNT(*) FROM ' . $ref['table_name']
            . ' WHERE USER_ID=?', [$id]) !== 0) {
            throw new RuntimeException('Independent user reference zero failed');
        }
    }
    define('TP_ENV', $envName);
    define('BUSINESS', 'aizhct');
    define('ENTERPRISE_NO', '10001');
    (new \think\App($root))->setEnvName($envName)->initialize();
    if (config('cache.default') !== 'file'
        || realpath((string)config('cache.stores.file.path'))
            !== realpath($root . '/runtime/cache')) {
        throw new RuntimeException('Private File cache boundary drift');
    }
    if (\think\facade\Cache::has($journal['token'])) {
        throw new RuntimeException('Independent token zero failed');
    }
    if (!unlink($journalPath) || !rmdir($journalDir)
        || file_exists($journalPath) || is_dir($journalDir)) {
        throw new RuntimeException('Verified journal removal failed');
    }
    echo json_encode(['lane' => $lane, 'phase' => $phase,
        'owned_user_staff_refs_token_zero' => true,
        'journal_absent' => true, 'business_http' => 0,
        'business_dml' => 0], JSON_UNESCAPED_SLASHES), "\n";
    exit(0);
}
if ($phase !== '--run' || $markerCount !== 0
    || file_exists($journalDir)
    || !mkdir($journalDir, 0700) || !chmod($journalDir, 0700)) {
    throw new RuntimeException('Marker/journal not pristine');
}
$token = 'CDXPERSONALT' . strtoupper(bin2hex(random_bytes(16)));
$journal = ['lane' => $lane, 'marker' => $marker,
    'phase' => 'before_insert', 'id' => 0, 'token' => $token,
    'created_at' => time()];
$save($journal);
$stage = 'owned-user-insert';
$db->beginTransaction();
try {
    $s = $db->prepare($insert);
    $s->execute(['', $marker, $journal['created_at']]);
    if ($s->rowCount() !== 1) throw new RuntimeException('Fixture insert affected-row mismatch');
    $matches = $query($db, 'SELECT USER_ID FROM ' . $userTable
        . ' WHERE NICK_NAME=? AND STORE_ID=10001', [$marker]);
    if (count($matches) !== 1 || (int)$matches[0]['user_id'] <= 0) {
        throw new RuntimeException('Fixture ID unresolved');
    }
    $id = (int)$matches[0]['user_id'];
    if ($count($db, 'SELECT COUNT(*) FROM ' . $staffTable
        . ' WHERE USER_ID=?', [$id]) !== 0) {
        throw new RuntimeException('No-staff branch gate violated');
    }
    $db->commit();
    $journal['id'] = $id;
    $journal['phase'] = 'fixture_committed';
    $save($journal);
} catch (Throwable $error) {
    if ($db->inTransaction()) $db->rollBack();
    $journal['phase'] = 'needs_recovery_review';
    $save($journal);
    throw $error;
}
$beforeRows = $query($connect(), 'SELECT * FROM ' . $userTable
    . ' WHERE USER_ID=? AND STORE_ID=10001', [$id]);
if (count($beforeRows) !== 1 || (string)$beforeRows[0]['nick_name'] !== $marker) {
    throw new RuntimeException('Fixture source row missing');
}
$before = $beforeRows[0];
define('TP_ENV', $envName);
define('BUSINESS', 'aizhct');
define('ENTERPRISE_NO', '10001');
(new \think\App($root))->setEnvName($envName)->initialize();
if (config('cache.default') !== 'file'
    || realpath((string)config('cache.stores.file.path'))
        !== realpath($root . '/runtime/cache')) {
    throw new RuntimeException('Private File cache boundary drift');
}
$expectedName = $marker . "-\u{1F9EA}";
$shape = null;
$shape = static function ($v) use (&$shape) {
    if (is_array($v)) {
        if (array_values($v) === $v) {
            return ['@array' => count($v), '@items' => array_map($shape, $v)];
        }
        $out = [];
        foreach ($v as $key => $value) $out[(string)$key] = $shape($value);
        ksort($out);
        return $out;
    }
    return gettype($v);
};
$out = ['lane' => $lane, 'phase' => $phase,
    'user_id' => $id, 'http' => 0, 'business_status' => null,
    'nickname_exact' => false, 'staff_rows_zero' => false,
    'token_deleted' => false, 'cleanup_committed' => false];
$issued = false;
$requestCompleted = false;
try {
    $stage = 'token';
    if (!\think\facade\Cache::set($token, ['user' => ['user_id' => $id],
            'password_version' => 0, 'login_type' => 'thirdparty'], 300)
        || !\think\facade\Cache::has($token)) {
        throw new RuntimeException('Private File token unavailable');
    }
    $issued = true;
    $journal['phase'] = 'token_issued'; $save($journal);
    $stage = 'business-http';
    $body = json_encode(['form' => [
        'nickname' => $expectedName, 'gender' => 1,
        'birthday' => '1990-01-01', 'height' => 170,
        'weight' => 60, 'mobile' => '']], JSON_UNESCAPED_SLASHES);
    $ctx = stream_context_create(['http' => ['method' => 'POST',
        'header' => 'Access-Token: ' . $token . "\r\n"
            . "Content-Type: application/json\r\n"
            . "platform: APP\r\nversion: 2.0.51\r\nenv-version: develop\r\n",
        'content' => $body, 'timeout' => 20,
        'ignore_errors' => true, 'follow_location' => 0]]);
    $h = @fopen($base . '/index.php?s=/api/user/personal', 'rb', false, $ctx);
    if ($h === false) throw new RuntimeException('HTTP open failed');
    $raw = stream_get_contents($h, 1048577);
    $meta = stream_get_meta_data($h);
    $eof = feof($h);
    fclose($h);
    $lines = $meta['wrapper_data'] ?? [];
    preg_match('/^HTTP\/\S+\s+(\d{3})(?:\s|$)/', (string)($lines[0] ?? ''), $m);
    $http = isset($m[1]) ? (int)$m[1] : 0;
    $lengthOk = true;
    foreach ($lines as $line) {
        if (preg_match('/^Content-Length:\s*(\d+)\s*$/i', (string)$line, $n)) {
            $lengthOk = is_string($raw) && strlen($raw) === (int)$n[1];
        }
    }
    $json = is_string($raw) && strlen($raw) <= 1048576 ? json_decode($raw, true) : null;
    $requestCompleted = $http > 0 && is_string($raw)
        && strlen($raw) <= 1048576 && $eof && $lengthOk
        && !($meta['timed_out'] ?? false)
        && is_array($json) && json_last_error() === JSON_ERROR_NONE;
    $out['http'] = $http;
    $out['business_status'] = $requestCompleted ? ($json['status'] ?? null) : null;
    $out['response_key_type_shape'] = $requestCompleted ? $shape($json) : null;
    $journal['phase'] = 'http_completed'; $save($journal);
    $stage = 'source-readback';
    $currentRows = $query($connect(), 'SELECT * FROM ' . $userTable
        . ' WHERE USER_ID=? AND STORE_ID=10001', [$id]);
    if (count($currentRows) !== 1) throw new RuntimeException('Owned row missing after HTTP');
    $out['nickname_exact'] = (string)$currentRows[0]['nick_name'] === $expectedName;
    $out['nickname_sha256'] = hash('sha256', (string)$currentRows[0]['nick_name']);
    $out['expected_nickname_sha256'] = hash('sha256', $expectedName);
    $out['staff_rows_zero'] = $count($connect(), 'SELECT COUNT(*) FROM '
        . $staffTable . ' WHERE USER_ID=?', [$id]) === 0;
} catch (Throwable $error) {
    $out['failure_stage'] = $stage;
    $out['failure_class'] = get_class($error);
} finally {
    $stage = 'completion-boundary';
    $boundary = @fopen($base . '/__poc_boundary', 'rb', false,
        stream_context_create(['http' => ['timeout' => 5,
            'ignore_errors' => true, 'follow_location' => 0]]));
    $boundaryOk = false;
    if ($boundary !== false) {
        $boundaryBody = stream_get_contents($boundary, 8193);
        $boundaryMeta = stream_get_meta_data($boundary);
        $boundaryEof = feof($boundary);
        fclose($boundary);
        $boundaryJson = is_string($boundaryBody) ? json_decode($boundaryBody, true) : null;
        $boundaryOk = is_string($boundaryBody) && strlen($boundaryBody) <= 8192
            && $boundaryEof && !($boundaryMeta['timed_out'] ?? false)
            && is_array($boundaryJson)
            && !empty($boundaryJson['external_stubs']);
    }
    $out['worker_completion_boundary'] = $boundaryOk;
    if ($issued) {
        \think\facade\Cache::delete($token);
        $out['token_deleted'] = !\think\facade\Cache::has($token);
    }
    if ($boundaryOk && $out['token_deleted']) {
        $stage = 'exact-cleanup';
        $latest = $query($connect(), 'SELECT * FROM ' . $userTable
            . ' WHERE USER_ID=? AND STORE_ID=10001', [$id]);
        if (count($latest) === 1) {
            $stableBefore = $before;
            $stableAfter = $latest[0];
            foreach (['nick_name', 'gender', 'update_time'] as $field) {
                unset($stableBefore[$field], $stableAfter[$field]);
            }
            $stable = $stableBefore === $stableAfter;
            $staffZero = $count($connect(), 'SELECT COUNT(*) FROM '
                . $staffTable . ' WHERE USER_ID=?', [$id]) === 0;
            $refsZero = true;
            foreach ($refs as $ref) {
                if (strcasecmp((string)$ref['table_name'], $userTable) === 0) continue;
                if ($count($connect(), 'SELECT COUNT(*) FROM '
                    . $ref['table_name'] . ' WHERE USER_ID=?', [$id]) !== 0) {
                    $refsZero = false;
                    break;
                }
            }
            if ($stable && $staffZero && $refsZero) {
                $clean = $connect();
                $clean->beginTransaction();
                try {
                    $s = $clean->prepare('DELETE FROM ' . $userTable
                        . ' WHERE USER_ID=? AND STORE_ID=10001 AND MOBILE=?');
                    $s->execute([$id, '']);
                    if ($s->rowCount() !== 1) throw new RuntimeException('Exact cleanup affected-row mismatch');
                    $clean->commit();
                    $journal['phase'] = 'cleanup_committed'; $save($journal);
                    $out['cleanup_committed'] = true;
                } catch (Throwable $error) {
                    if ($clean->inTransaction()) $clean->rollBack();
                    $out['cleanup_failure_class'] = get_class($error);
                }
            }
        }
    }
}
$out['pass'] = !isset($out['failure_class'])
    && $requestCompleted && $out['http'] === 200
    && (int)$out['business_status'] === 200
    && $out['nickname_exact'] && $out['staff_rows_zero']
    && $out['token_deleted'] && $out['cleanup_committed'];
echo json_encode($out, JSON_UNESCAPED_SLASHES), "\n";
exit($out['pass'] ? 0 : 3);
