<?php
declare(strict_types=1);

$phase = (string)($argv[1] ?? '');
$lane = (string)($argv[2] ?? '');
$marker = (string)($argv[3] ?? '');
if (!in_array($phase, ['--run', '--audit'], true) || !in_array($lane, ['B', 'C'], true)
    || !preg_match('/^CDXHIMG[A-F0-9]{9}$/D', $marker)
    || ($phase === '--run' && getenv('CDX_HARDWARE_IMG_RUN') !== 'TWO_FAKE_DB_ROWS_V1')) {
    fwrite(STDERR, "DENIED business_http=0 business_dml=0\n"); exit(78);
}
if ($lane === 'B') {
    $config = include '/tmp/zhct-http-store-mysql.dQTTBP/application/config/local/database.php';
    if (!is_array($config) || ($config['database'] ?? '') !== 'zhct'
        || hash('sha256', (string)($config['hostname'] ?? ''))
            !== '47e8be48b0cfd56dcdb9d9d426e6637b245f340b4efad4cd2f084ec5851ecc8e') {
        throw new RuntimeException('B code-local Store identity drift');
    }
    $db = new PDO('mysql:host=' . $config['hostname'] . ';port=3306;dbname=zhct;charset=utf8',
        $config['username'], $config['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_LOWER]);
    $port = 18081;
} else {
    if (getenv('POC_DIALECT') !== 'dm' || getenv('POC_HOST') !== '127.0.0.1'
        || getenv('POC_PORT') !== '5237' || getenv('POC_SCHEMA') !== 'ZHCT_APP'
        || getenv('POC_USER') !== 'ZHCT_APP') {
        throw new RuntimeException('C isolated Store identity drift');
    }
    $db = new PDO('dm:host=127.0.0.1;port=5237;schema=ZHCT_APP',
        getenv('POC_USER'), getenv('POC_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() !== 'ZHCT_APP') {
        throw new RuntimeException('C Store schema drift');
    }
    $port = 18080;
}
$guid = static function (string $seed): string {
    $hex = strtoupper(substr(hash('sha256', $seed), 0, 32));
    return substr($hex, 0, 8) . '-' . substr($hex, 8, 4) . '-'
        . substr($hex, 12, 4) . '-' . substr($hex, 16, 4)
        . '-' . substr($hex, 20, 12);
};
$uuids = [1 => $guid($marker . 'face'), 2 => $guid($marker . 'cabinet')];
$hardwareUuids = [1 => $guid($marker . 'face-hardware'),
    2 => $guid($marker . 'cabinet-hardware')];
$ownRows = static function () use ($db, $uuids): array {
    $stmt = $db->prepare('SELECT id,uuid,hardware_uuid,staff_uuid,head_img,'
        . 'head_img_url,feature,type,is_del FROM ydy_hardware_img WHERE uuid IN (?,?) ORDER BY type');
    $stmt->execute([$uuids[1], $uuids[2]]);
    return array_map(static function (array $row): array {
        return array_change_key_case($row, CASE_LOWER);
    }, $stmt->fetchAll(PDO::FETCH_ASSOC));
};
$before = $ownRows();
if ($phase === '--audit') {
    echo json_encode(['lane' => $lane, 'phase' => 'audit', 'marker' => $marker,
        'owned_hardware_img_count' => count($before),
        'business_http' => 0, 'business_dml' => 0]), PHP_EOL;
    exit($before ? 2 : 0);
}
if ($before) throw new RuntimeException('own image marker already exists');
$staffSql = 'SELECT uuid FROM ydy_staff WHERE is_show=1 AND status=1 ORDER BY id DESC'
    . ($lane === 'B' ? ' LIMIT 1' : ' FETCH FIRST 1 ROWS ONLY');
$staffUuid = $db->query($staffSql)->fetchColumn();
if (!is_string($staffUuid) || $staffUuid === '') throw new RuntimeException('active original staff absent');
$naturalBefore = $db->query('SELECT id,uuid,type FROM ydy_hardware_img ORDER BY id')
    ->fetchAll(PDO::FETCH_ASSOC);
$naturalSha = hash('sha256', json_encode($naturalBefore));
$insert = $db->prepare('INSERT INTO ydy_hardware_img'
    . ' (uuid,hardware_uuid,staff_uuid,head_img,head_img_url,feature,type,create_time,is_del)'
    . " VALUES (?,?,?,?,?,?,?,? ,0)");
$http = static function (string $path, string $method = 'POST', array $form = []) use ($port): array {
    if (!in_array($path, ['/p/api/getUploadImg', '/p/api/getDishImg',
        '/p/api/getUploadImgByUuid'], true) || !in_array($method, ['GET', 'POST'], true)) {
        throw new RuntimeException('unsupported image DB route');
    }
    $ctx = stream_context_create(['http' => [
        'method' => $method, 'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
        'content' => http_build_query($form, '', '&', PHP_QUERY_RFC3986),
        'ignore_errors' => true, 'timeout' => 45, 'follow_location' => 0,
    ]]);
    $handle = @fopen('http://127.0.0.1:' . $port . $path, 'rb', false, $ctx);
    if (!is_resource($handle)) throw new RuntimeException('isolated image DB HTTP unavailable');
    $raw = stream_get_contents($handle, 2097153);
    fclose($handle);
    if (!is_string($raw) || strlen($raw) > 2097152) throw new RuntimeException('image DB response cap');
    $body = json_decode($raw, true);
    if (!is_array($body) || (int)($body['code'] ?? -1) !== 0) {
        throw new RuntimeException('image DB HTTP business failure at ' . $path
            . ' code=' . (string)($body['code'] ?? 'nonjson')
            . ' message=' . substr((string)($body['message'] ?? ''), 0, 100));
    }
    return $body;
};
$typeHash = static function (array $row): string {
    $types = [];
    foreach ($row as $key => $value) $types[$key] = gettype($value);
    ksort($types);
    return hash('sha256', json_encode($types));
};
$error = null;
$result = [];
try {
    $now = date('Y-m-d H:i:s');
    $db->beginTransaction();
    foreach ([1, 2] as $type) {
        $insert->execute([$uuids[$type], $hardwareUuids[$type], $staffUuid,
            $marker . '_NOT_REAL_IMAGE', '', $marker . '_NOT_REAL_FEATURE', $type, $now]);
    }
    $db->commit();
    $rows = $ownRows();
    if (count($rows) !== 2) throw new RuntimeException('owned two image rows missing');
    foreach ($rows as $row) {
        $type = (int)$row['type'];
        if (!in_array($type, [1, 2], true)
            || (string)$row['hardware_uuid'] !== $hardwareUuids[$type]
            || (string)$row['staff_uuid'] !== $staffUuid
            || (string)$row['head_img'] !== $marker . '_NOT_REAL_IMAGE'
            || (string)$row['head_img_url'] !== ''
            || (string)$row['feature'] !== $marker . '_NOT_REAL_FEATURE') {
            throw new RuntimeException('owned image table source mismatch');
        }
    }
    $faceList = $http('/p/api/getUploadImg')['data'] ?? null;
    $dishList = $http('/p/api/getDishImg')['data'] ?? null;
    foreach ([1 => $faceList, 2 => $dishList] as $type => $list) {
        if (!is_array($list)) throw new RuntimeException('image UUID list not array');
        $found = array_values(array_filter($list,
            static function ($item) use ($hardwareUuids, $type): bool {
                return is_array($item)
                    && (string)($item['hardware_uuid'] ?? '') === $hardwareUuids[$type];
            }));
        if (count($found) !== 1) throw new RuntimeException('owned image UUID missing from list');
        $result[$type === 1 ? 'getUploadImg' : 'getDishImg'] = $typeHash($found[0]);
    }
    $detail = $http('/p/api/getUploadImgByUuid', 'POST', ['uuid' => $hardwareUuids[1]])['data'] ?? null;
    if (!is_array($detail) || (string)($detail['uuid'] ?? '') !== $uuids[1]
        || (string)($detail['hardware_uuid'] ?? '') !== $hardwareUuids[1]
        || (string)($detail['staff_uuid'] ?? '') !== $staffUuid
        || (string)($detail['head_img'] ?? '') !== $marker . '_NOT_REAL_IMAGE'
        || (string)($detail['head_img_url'] ?? '') !== '') {
        throw new RuntimeException('owned image detail differs from original row');
    }
    $result['getUploadImgByUuid'] = $typeHash($detail);
} catch (Throwable $caught) {
    $error = $caught;
} finally {
    if ($db->inTransaction()) $db->rollBack();
    foreach ($ownRows() as $row) {
        $type = (int)$row['type'];
        $delete = $db->prepare('DELETE FROM ydy_hardware_img'
            . ' WHERE id=? AND uuid=? AND hardware_uuid=?');
        $delete->execute([(int)$row['id'], $uuids[$type], $hardwareUuids[$type]]);
    }
}
if ($ownRows()) throw new RuntimeException('own hardware image cleanup failed');
$naturalAfter = $db->query('SELECT id,uuid,type FROM ydy_hardware_img ORDER BY id')
    ->fetchAll(PDO::FETCH_ASSOC);
if (hash('sha256', json_encode($naturalAfter)) !== $naturalSha) {
    throw new RuntimeException('natural image rows changed');
}
if ($error !== null) throw $error;
echo json_encode(['lane' => $lane, 'marker' => $marker,
    'http_business_ok' => 3, 'type_hashes' => $result,
    'owned_two_rows_cleanup_zero' => true,
    'business_dml' => 'two-fake-DB-image-rows-insert-and-exact-delete',
    'real_face_image_file_oss' => 0], JSON_UNESCAPED_SLASHES), PHP_EOL;
