<?php
declare(strict_types=1);

// DEFAULT DENY for HTTP/token phases until exact fixture and reviewed SHA gates pass.
$phase = (string)($argv[1] ?? '');
$lane = (string)($argv[2] ?? '');
$marker = (string)($argv[3] ?? '');
if (!in_array($phase, ['--probe', '--run', '--audit-token'], true)
    || !in_array($lane, ['B', 'C'], true)
    || !preg_match('/^CDXSPEC[0-9A-F]{12}$/', $marker)) {
    fwrite(STDERR, "DENIED: exact phase/lane/marker required\n");
    exit(78);
}
if ($phase !== '--probe') {
    $reviewed = (string)getenv('CDX_SPEC_HTTP_REVIEWED_SHA256');
    if ((string)getenv('CDX_SPEC_HTTP_APPROVAL') !== 'OWNED_SPEC_HTTP_V1'
        || !preg_match('/^[0-9a-f]{64}$/', $reviewed)
        || ($lane === 'B' && hash_file('sha256', __FILE__) !== $reviewed)
        || ($lane === 'C' && (string)getenv('CDX_SPEC_HTTP_SOURCE_CHECKED') !== '1')) {
        fwrite(STDERR, "DENIED: exact reviewed SHA/HTTP gate required\n");
        exit(78);
    }
}
$stage = 'start';
set_exception_handler(static function (Throwable $e) use (&$stage): void {
    fwrite(STDERR, 'SPEC_HTTP_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;
foreach ([
    'app/store/controller/goods/Spec.php' => '6138dfe6193274b871cff2fd20d350308f49b81346872d609ce06eff961e580c',
    'app/common/model/GoodsSpecRel.php' => '58c1ea08bb58963f43532b11dd4c0a008f1aa33f97bb553ba9361640c7b05f01',
] as $file => $sha) {
    if (!is_file($root . '/' . $file) || hash_file('sha256', $root . '/' . $file) !== $sha) {
        throw new RuntimeException('Isolated source drift');
    }
}
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=utf8', $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 {
        $d = 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 ($d->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn() !== 'AIZHCT_APP') {
            throw new RuntimeException('C schema drift');
        }
        return $d;
    };
    $envName = 'poc';
}
$t = static function (string $logical) use ($lane): string {
    if (!in_array($logical, ['goods', 'spec', 'spec_value', 'goods_spec_rel'], true)) {
        throw new RuntimeException('Unexpected table');
    }
    return 'yoshop_' . ($lane === 'B' ? $logical : strtoupper($logical));
};
$fixturePath = sys_get_temp_dir() . '/cdx-spec-fixture-'
    . strtolower($lane) . '-' . strtolower($marker) . '/journal.json';
$fixture = is_file($fixturePath)
    ? json_decode((string)file_get_contents($fixturePath), true) : null;
if (!is_array($fixture) || ($fixture['lane'] ?? '') !== $lane
    || ($fixture['marker'] ?? '') !== $marker
    || ($fixture['phase'] ?? '') !== 'fixture_committed'
    || !is_array($fixture['ids'] ?? null)) {
    throw new RuntimeException('Exact committed fixture journal absent');
}
$ids = $fixture['ids'];
foreach (['goods', 'spec', 'value1', 'value2', 'rel1', 'rel2'] as $key) {
    if (!isset($ids[$key]) || (int)$ids[$key] <= 0) {
        throw new RuntimeException('Fixture ID absent');
    }
    $ids[$key] = (int)$ids[$key];
}
$query = static function (PDO $d, string $sql, array $args = []): array {
    $s = $d->prepare($sql);
    $s->execute($args);
    return $s->fetchAll(PDO::FETCH_ASSOC);
};
$owned = static function (PDO $d) use ($query, $t, $ids, $marker): array {
    $checks = [
        ['goods', 'GOODS_ID', $ids['goods'], 'GOODS_NAME', $marker],
        ['spec', 'SPEC_ID', $ids['spec'], 'SPEC_NAME', $marker . 'SPEC'],
        ['spec_value', 'SPEC_VALUE_ID', $ids['value1'], 'SPEC_VALUE', $marker . 'VAL1'],
        ['spec_value', 'SPEC_VALUE_ID', $ids['value2'], 'SPEC_VALUE', $marker . 'VAL2'],
        ['goods_spec_rel', 'ID', $ids['rel1'], 'SPEC_VALUE_ID', $ids['value1']],
        ['goods_spec_rel', 'ID', $ids['rel2'], 'SPEC_VALUE_ID', $ids['value2']],
    ];
    $out = [];
    foreach ($checks as $key => [$logical, $pk, $id, $field, $value]) {
        $rows = $query($d, 'SELECT * FROM ' . $t($logical)
            . ' WHERE ' . $pk . '=? AND STORE_ID=10001 AND ' . $field . '=?', [$id, $value]);
        if (count($rows) !== 1) throw new RuntimeException('Owned row absent/ambiguous');
        $out[$key] = $rows[0];
    }
    if ((int)$out[0]['spec_type'] !== 20 || (int)$out[0]['status'] !== 20
        || (int)$out[0]['stock_total'] !== 0 || (int)$out[0]['is_delete'] !== 0
        || (int)$out[2]['spec_id'] !== $ids['spec']
        || (int)$out[3]['spec_id'] !== $ids['spec']) {
        throw new RuntimeException('Owned fixture safety/link drift');
    }
    foreach ([4 => 'value1', 5 => 'value2'] as $key => $valueKey) {
        if ((int)$out[$key]['goods_id'] !== $ids['goods']
            || (int)$out[$key]['spec_id'] !== $ids['spec']
            || (int)$out[$key]['spec_value_id'] !== $ids[$valueKey]) {
            throw new RuntimeException('Owned relation drift');
        }
    }
    return $out;
};
$stage = 'fixture-readback';
$db = $connect();
$before = $owned($db);
$sourceSha = hash('sha256', serialize($before));
if ($sourceSha !== (string)($fixture['own_sha256'] ?? '')) {
    throw new RuntimeException('Fixture journal source SHA drift');
}
define('TP_ENV', $envName);
define('BUSINESS', 'aizhct');
define('ENTERPRISE_NO', '10001');
require_once $root . '/vendor/autoload.php';
(new \think\App($root))->setEnvName($envName)->initialize();
if (config('cache.default') !== 'file') throw new RuntimeException('Private File cache absent');
$tokenDir = sys_get_temp_dir() . '/cdx-spec-token-'
    . strtolower($lane) . '-' . strtolower($marker);
$tokenJournal = $tokenDir . '/journal.json';
if ($phase === '--probe') {
    echo json_encode(['lane' => $lane, 'phase' => $phase,
        'marker' => $marker, 'fixture_rows' => 6,
        'fixture_sha256' => $sourceSha, 'token_journal_absent' => !file_exists($tokenDir),
        'business_http' => 0, 'business_dml' => 0], JSON_UNESCAPED_SLASHES), "\n";
    exit(file_exists($tokenDir) ? 3 : 0);
}
if ($phase === '--audit-token') {
    if (!is_file($tokenJournal)) throw new RuntimeException('Token journal absent');
    $j = json_decode((string)file_get_contents($tokenJournal), true);
    if (!is_array($j) || ($j['lane'] ?? '') !== $lane
        || ($j['marker'] ?? '') !== $marker
        || !preg_match('/^CDXSPECTOKEN[0-9A-F]{32}$/', (string)($j['token'] ?? ''))
        || (string)($j['fixture_sha256'] ?? '') !== $sourceSha) {
        throw new RuntimeException('Token journal identity drift');
    }
    $boundary = @fopen($base . '/__poc_boundary', 'rb', false,
        stream_context_create(['http' => ['timeout' => 5,
            'ignore_errors' => true, 'follow_location' => 0]]));
    if ($boundary === false) throw new RuntimeException('Isolated worker boundary absent');
    $boundaryBody = stream_get_contents($boundary, 8193);
    $meta = stream_get_meta_data($boundary);
    $eof = feof($boundary);
    fclose($boundary);
    $boundaryJson = is_string($boundaryBody) ? json_decode($boundaryBody, true) : null;
    if (!is_string($boundaryBody) || strlen($boundaryBody) > 8192
        || !$eof || ($meta['timed_out'] ?? false)
        || ($lane === 'C' && (!is_array($boundaryJson)
            || empty($boundaryJson['external_stubs'])))) {
        throw new RuntimeException('Worker completion boundary uncertain');
    }
    $tokenZero = !\think\facade\Cache::has($j['token']);
    $sourceSame = hash('sha256', serialize($owned($connect()))) === $sourceSha;
    if (!$tokenZero || !$sourceSame) {
        throw new RuntimeException('Independent token/source audit failed');
    }
    if (!unlink($tokenJournal) || !rmdir($tokenDir)
        || file_exists($tokenJournal) || is_dir($tokenDir)) {
        throw new RuntimeException('Exact token journal removal failed');
    }
    echo json_encode(['lane' => $lane, 'phase' => $phase,
        'token_zero' => true, 'fixture_unchanged' => true,
        'journal_absent' => true, 'business_http' => 0, 'business_dml' => 0],
        JSON_UNESCAPED_SLASHES), "\n";
    exit(0);
}
if (file_exists($tokenDir) || !mkdir($tokenDir, 0700)
    || !chmod($tokenDir, 0700)) {
    throw new RuntimeException('Token journal not pristine');
}
$token = 'CDXSPECTOKEN' . strtoupper(bin2hex(random_bytes(16)));
$j = ['lane' => $lane, 'marker' => $marker,
    'token' => $token, 'fixture_sha256' => $sourceSha,
    'phase' => 'before_http'];
$saveJournal = static function () use (&$j, $tokenJournal): void {
    $body = json_encode($j, JSON_UNESCAPED_SLASHES);
    $tmp = $tokenJournal . '.tmp';
    if (!is_string($body) || file_put_contents($tmp, $body, LOCK_EX) !== strlen($body)
        || !chmod($tmp, 0600) || !rename($tmp, $tokenJournal)) {
        throw new RuntimeException('Token journal write failed');
    }
};
$saveJournal();
$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);
};
$request = static function (?string $auth) use ($base, $ids): array {
    $url = $base . '/index.php?s=/store/goods.Spec/list&goodsId=' . $ids['goods'];
    $header = $auth === null ? '' : 'Access-Token: ' . $auth . "\r\n";
    $ctx = stream_context_create(['http' => ['method' => 'GET',
        'header' => $header, 'timeout' => 20,
        'ignore_errors' => true, 'follow_location' => 0]]);
    $start = microtime(true);
    $h = @fopen($url, 'rb', false, $ctx);
    if ($h === false) return ['complete' => false, 'http' => 0, 'json' => null];
    $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;
    $complete = $http > 0 && is_string($raw) && strlen($raw) <= 1048576
        && $eof && !($meta['timed_out'] ?? false) && $lengthOk
        && is_array($json) && json_last_error() === JSON_ERROR_NONE;
    return ['complete' => $complete, 'http' => $http,
        'json' => $complete ? $json : null,
        'elapsed_ms' => (int)round((microtime(true) - $start) * 1000)];
};
$out = ['lane' => $lane, 'phase' => $phase, 'marker' => $marker,
    'token_deleted' => false, 'fixture_unchanged' => false,
    'business_dml' => 0];
$issued = false;
try {
    $stage = 'token';
    if (!\think\facade\Cache::set($token, ['user' => [
            'store_user_id' => 2147480011, 'store_id' => 10001,
            'user_name' => $marker, 'real_name' => $marker,
            'is_super' => 1], 'store_id' => 10001,
            'is_login' => true], 300)
        || !\think\facade\Cache::has($token)) {
        throw new RuntimeException('Short File token unavailable');
    }
    $issued = true;
    $j['phase'] = 'token_issued'; $saveJournal();
    $stage = 'unauth-http';
    $unauth = $request(null);
    if (!$unauth['complete'] || (int)($unauth['json']['status'] ?? 200) === 200) {
        throw new RuntimeException('Unauthenticated request not conclusively rejected');
    }
    $stage = 'business-http';
    $response = $request($token);
    $list = $response['json']['data']['list'] ?? null;
    if (!$response['complete'] || $response['http'] !== 200
        || (int)($response['json']['status'] ?? -1) !== 200
        || !is_array($list) || count($list) !== 1
        || (int)($list[0]['spec_id'] ?? 0) !== $ids['spec']
        || (string)($list[0]['spec_name'] ?? '') !== $marker . 'SPEC'
        || !is_array($list[0]['valueList'] ?? null)
        || count($list[0]['valueList']) !== 2) {
        throw new RuntimeException('Spec HTTP business result/source group mismatch');
    }
    $actual = [];
    foreach ($list[0]['valueList'] as $value) {
        $actual[] = [(int)($value['spec_value_id'] ?? 0),
            (string)($value['spec_value'] ?? '')];
    }
    $want = [[$ids['value1'], $marker . 'VAL1'],
        [$ids['value2'], $marker . 'VAL2']];
    sort($actual);
    sort($want);
    if ($actual !== $want) throw new RuntimeException('Spec values differ from original table');
    $out['fixture_unchanged'] = hash('sha256', serialize($owned($connect()))) === $sourceSha;
    if (!$out['fixture_unchanged']) throw new RuntimeException('Business source drift after GET');
    $out['routes'] = ['spec_list' => [
        'http' => $response['http'], 'status' => 200,
        'group_count' => 1, 'value_count' => 2,
        'source_fields_match' => true, 'elapsed_ms' => $response['elapsed_ms'],
        'unauth_status' => (int)$unauth['json']['status'],
        'unauth_full_json_key_type_shape' => $shape($unauth['json']),
        'full_json_key_type_shape' => $shape($response['json'])]];
    $j['phase'] = 'completed'; $saveJournal();
} catch (Throwable $e) {
    $out['failure_stage'] = $stage;
    $out['failure_class'] = get_class($e);
} finally {
    if ($issued) {
        \think\facade\Cache::delete($token);
        $out['token_deleted'] = !\think\facade\Cache::has($token);
    }
}
$out['pass'] = !isset($out['failure_class'])
    && $out['token_deleted'] && $out['fixture_unchanged']
    && isset($out['routes']['spec_list']);
echo json_encode($out, JSON_UNESCAPED_SLASHES), "\n";
exit($out['pass'] ? 0 : 3);
