<?php

// ==========================================
// 配置：Path 前缀 → 域名池（数组）
// ==========================================

$pathPools = [
    '/xmpdkstfe/'   => [
        'https://au.daoyuwh.com',
        'https://ku.daoyuwh.com',
        'https://cu.daoyuwh.com',
    ],
    '/bzyytfd/'   => [
        'https://au.linkdaoyu.com',
        'https://ku.linkdaoyu.com',
        'https://cu.linkdaoyu.com',
    ],
    '/bzyytfd/' => [
        'https://au.linkdaoyu.com',
        'https://ku.linkdaoyu.com',
        'https://cu.linkdaoyu.com',
    ],
    '/sxystfa/' => [
        'https://au.fangzwh.com',
        'https://cu.fangzwh.com',
        'https://ku.fangzwh.com',
    ],
];

// 兜底域名池（未匹配到任何 Path 时）
$defaultPool = [
    'https://au.linkdaoyu.com',
    'https://ku.linkdaoyu.com',
    'https://cu.linkdaoyu.com',
];

// 池内选择策略：'time' | 'random' | 'hash'
// time   = 按分钟轮询（同原逻辑，同一分钟内同组同域名）
// random = 每次请求随机（均匀打散，但可能重复）
// hash   = 按 Path 哈希（同一 Path 永远固定到同一域名）
$strategy = 'time';


// ==========================================
// 1. 获取当前请求的 Path
// ==========================================

$requestUri = $_SERVER['REQUEST_URI'];                          // 如 /api/user/info?id=1
$pathOnly   = parse_url($requestUri, PHP_URL_PATH) ?: '/';      // 如 /api/user/info


// ==========================================
// 2. 查找匹配的域名池（最长前缀匹配优先）
// ==========================================

$matchedPool = null;
$matchedPrefix = '';

foreach ($pathPools as $prefix => $pool) {
    // 判断 $pathOnly 是否以 $prefix 开头
    if (strpos($pathOnly, $prefix) === 0) {
        // 选最长匹配的前缀，避免 /api/ 和 /api/v2/ 冲突时短路径抢匹配
        if (strlen($prefix) > strlen($matchedPrefix)) {
            $matchedPrefix = $prefix;
            $matchedPool = $pool;
        }
    }
}

// 未匹配到任何规则，使用兜底池
if ($matchedPool === null) {
    $matchedPool = $defaultPool;
}


// ==========================================
// 3. 从匹配到的域名池里，按策略选一个域名
// ==========================================

$count = count($matchedPool);

switch ($strategy) {
    case 'time':
        // 按当前分钟数取模，同组同分钟走同一域名（缓存友好）
        $index = intval(date('i')) % $count;
        break;
        
    case 'random':
        // 完全随机，请求均摊
        $index = mt_rand(0, $count - 1);
        break;
        
    case 'hash':
        // 按 Path 哈希，相同 Path 永远落到同一域名（会话/缓存固定）
        $index = abs(crc32($pathOnly)) % $count;
        break;
        
    default:
        $index = 0;
}

$targetDomain = $matchedPool[$index];


// ==========================================
// 4. 执行 302 跳转（保留原始路径和参数）
// ==========================================

header('Location: ' . $targetDomain . $requestUri, true, 302);
exit;