<?php
declare(strict_types=1);

function read6_safe2_shape($value)
{
    if (!is_array($value)) return gettype($value);
    if ($value === []) return [];
    if (array_keys($value) === range(0, count($value) - 1)) {
        return ['[]' => read6_safe2_shape($value[0])];
    }
    $shape = [];
    foreach ($value as $key => $item) $shape[$key] = read6_safe2_shape($item);
    ksort($shape, SORT_STRING);
    return $shape;
}

function read6_safe2_contract(string $route, int $http, string $raw): array
{
    $red = ['state' => 'contract_red', 'route' => $route];
    if ($http !== 200 || strlen($raw) > 65536 || $raw === '') return $red;
    $body = json_decode($raw, true);
    if (!is_array($body) || (int)($body['status'] ?? -1) !== 200
        || !isset($body['data']) || !is_array($body['data'])) return $red;
    $data = $body['data'];
    if ($route === 'setting') {
        if (!isset($data['setting']) || !is_array($data['setting'])) return $red;
        $expected = ['aifaceview', 'aifaceset', 'apifacedefault',
            'withdrawRecord', 'details', 'recharge', 'orderDetail',
            'face_type', 'zhct_host'];
        foreach ($expected as $key) {
            if (!array_key_exists($key, $data['setting'])) return $red;
            if ($key !== 'face_type' && !is_string($data['setting'][$key])) return $red;
        }
        if (!is_numeric($data['setting']['face_type'])) return $red;
        $branch = 'setting_candidate';
    } elseif ($route === 'cashout_list') {
        if (!isset($data['list']) || !is_array($data['list'])) return $red;
        $list = $data['list'];
        foreach (['current_page', 'data', 'last_page', 'per_page', 'total'] as $key) {
            if (!array_key_exists($key, $list)) return $red;
        }
        if (!is_array($list['data']) || !is_numeric($list['total'])
            || (int)$list['per_page'] !== 50 || (int)$list['current_page'] !== 1
            || count($list['data']) > 50
            || ((int)$list['total'] > 0 && count($list['data']) === 0)) return $red;
        $branch = count($list['data']) === 0 ? 'empty_only' : 'nonempty_candidate';
    } else {
        return $red;
    }
    return ['state' => 'shape_ok', 'route' => $route, 'branch' => $branch,
        'shape' => read6_safe2_shape($data),
        'data_sha256' => hash('sha256', json_encode($data,
            JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))];
}
