<?php
declare(strict_types=1);

// Offline, default-deny plan only. No database, HTTP, cache, fixture write, or external call.
function read6_fixture_decide(array $input): array
{
    $blocked = static function (string $reason): array {
        return ['status' => 'blocked', 'reason' => $reason, 'http' => 0, 'dml' => 0];
    };
    if (array_keys($input) !== ['marker', 'lanes']
        || $input['marker'] !== 'CDX_READ6_20261004'
        || !is_array($input['lanes'])
        || array_keys($input['lanes']) !== ['A', 'B', 'C']) {
        return $blocked('manifest_shape');
    }
    $requiredChecks = [
        'runtime_identity', 'owned_ai_user', 'owned_store_user', 'store_mapping',
        'file_token', 'password_version_match', 'short_ttl', 'external_stubs',
        'queue_isolated', 'file_logs_baselined', 'two_database_probe',
        'source_fingerprint', 'cleanup_journal',
    ];
    $requiredCounts = [
        'cashout_order', 'recharge_order', 'course', 'archive_related',
        'user_data_related',
    ];
    foreach ($input['lanes'] as $lane) {
        if (!is_array($lane)
            || array_keys($lane) !== [
                'database', 'physical', 'owner', 'checks', 'counts',
                'weight_goal_exists', 'staff_exists', 'coze_whitelisted',
                'local_wallet_allowed',
            ]
            || !is_string($lane['physical']) || $lane['physical'] === ''
            || !is_string($lane['owner']) || $lane['owner'] === ''
            || !is_array($lane['checks']) || !is_array($lane['counts'])
            || array_keys($lane['checks']) !== $requiredChecks
            || array_keys($lane['counts']) !== $requiredCounts) {
            return $blocked('lane_shape');
        }
        foreach ($requiredChecks as $check) {
            if ($lane['checks'][$check] !== true) return $blocked('safety_gate');
        }
        foreach ($requiredCounts as $count) {
            if (!is_int($lane['counts'][$count]) || $lane['counts'][$count] < 0) {
                return $blocked('owned_count_unknown');
            }
        }
        foreach (['weight_goal_exists', 'staff_exists', 'coze_whitelisted',
            'local_wallet_allowed'] as $condition) {
            if (!is_bool($lane[$condition])) return $blocked('condition_unknown');
        }
    }
    $lanes = $input['lanes'];
    if ($lanes['A']['database'] !== 'dev-mysql'
        || $lanes['B']['database'] !== 'dev-mysql'
        || $lanes['C']['database'] !== 'dm-test'
        || $lanes['A']['physical'] !== $lanes['B']['physical']
        || $lanes['A']['owner'] !== $lanes['B']['owner']
        || $lanes['C']['physical'] === $lanes['A']['physical']
        || $lanes['C']['owner'] === $lanes['A']['owner']) {
        return $blocked('lane_isolation');
    }

    $route = static function (string $method, string $path, bool $ready,
        string $reason = '', string $branch = 'source_unproven'): array {
        return ['method' => $method, 'path' => $path,
            'state' => $ready ? 'candidate_for_live_recheck' : 'skip',
            'reason' => $ready ? '' : $reason,
            'branch' => $ready ? $branch : 'not_run'];
    };
    $out = [];
    foreach ($lanes as $name => $lane) {
        $counts = $lane['counts'];
        $out[$name] = [
            $route('POST', '/api/Setting/aiface', true),
            $route('GET', '/api/Cashout/list', $counts['cashout_order'] <= 100,
                'owned_cashout_rows_over_100', $counts['cashout_order'] > 0
                    ? 'nonempty_source_candidate' : 'empty_only'),
            $route('POST', '/api/Cashout/read', $counts['recharge_order'] <= 100
                && $lane['local_wallet_allowed'], 'recharge_rows_or_wallet_guard',
                $counts['recharge_order'] > 0 ? 'nonempty_source_candidate' : 'empty_only'),
            $route('GET', '/api/user.UserCourse/schedule', $counts['course'] <= 100
                && $lane['weight_goal_exists'], 'course_rows_or_goal_missing',
                $counts['course'] > 0 ? 'nonempty_source_candidate' : 'empty_only'),
            $route('GET', '/api/health.Archive/info', $counts['archive_related'] <= 100
                && $lane['weight_goal_exists'] && $lane['staff_exists'],
                'archive_rows_or_goal_or_staff_missing'),
            $route('POST', '/api/User/data', $counts['user_data_related'] <= 100
                && $lane['coze_whitelisted'] && $lane['staff_exists'],
                'user_data_rows_or_whitelist_or_staff_missing'),
        ];
    }
    return ['status' => 'offline_plan_only', 'lanes' => $out,
        'http' => 0, 'dml' => 0];
}

if (isset($_SERVER['SCRIPT_FILENAME']) && realpath($_SERVER['SCRIPT_FILENAME']) === __FILE__) {
    if (($argv[1] ?? '') !== '--plan' || count($argv) !== 3
        || getenv('CDX_READ6_OFFLINE_ONLY') !== '1') {
        echo json_encode(['status' => 'default_deny', 'http' => 0, 'dml' => 0]), PHP_EOL;
        exit(78);
    }
    $path = $argv[2];
    $stat = is_link($path) ? false : @stat($path);
    if (!is_array($stat) || !is_file($path) || ($stat['mode'] & 0777) !== 0600
        || $stat['uid'] !== getmyuid() || $stat['size'] > 16384) {
        echo json_encode(['status' => 'blocked', 'reason' => 'private_manifest_required',
            'http' => 0, 'dml' => 0]), PHP_EOL;
        exit(2);
    }
    $input = json_decode((string)file_get_contents($path), true);
    $plan = read6_fixture_decide(is_array($input) ? $input : []);
    echo json_encode($plan, JSON_UNESCAPED_SLASHES), PHP_EOL;
    exit($plan['status'] === 'offline_plan_only' ? 0 : 2);
}
