<?php

// ================= CACHE =================
$cacheFile = 'cache.txt';
$cacheTime = 6 * 60;

if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < $cacheTime) {
    $response = file_get_contents($cacheFile);
} else {
    $url = "https://melomelo.xyz/V2rayapp/mapleVPN.php";
    $response = file_get_contents($url);
    if ($response === false) die("خطا در دریافت داده از API");
    file_put_contents($cacheFile, $response);
}

define('CFG_NAME', '@shenvpn');

// ================= Helpers =================
function is_uuid($s) {
    return (bool)preg_match('/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i', $s);
}
function is_host_like($h) {
    if ($h === '') return false;
    if (preg_match('/^\[[0-9a-f:]+\]$/i', $h)) return true;
    if (filter_var($h, FILTER_VALIDATE_IP)) return true;
    return (bool)preg_match('/^(?=.{1,253}$)([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/i', $h);
}
function is_port($p) {
    if (!ctype_digit((string)$p)) return false;
    $n = (int)$p;
    return $n >= 1 && $n <= 65535;
}
function base64url_to_base64($s) {
    $s = strtr($s, '-_', '+/');
    $pad = strlen($s) % 4;
    if ($pad) $s .= str_repeat('=', 4 - $pad);
    return $s;
}
function safe_urldecode_once($s) {
    return preg_replace_callback('/%[0-9A-Fa-f]{2}/', fn($m) => rawurldecode($m[0]), $s);
}

// ================= Rename =================
function renameLinkConfig($cfg) {
    if (stripos($cfg, 'vmess://') === 0) {
        $b64 = base64url_to_base64(trim(substr($cfg, 8)));
        $dec = base64_decode($b64, true);
        if ($dec === false) return $cfg;
        $json = json_decode($dec, true);
        if (!is_array($json)) return $cfg;
        $json['ps'] = CFG_NAME;
        return 'vmess://' . base64_encode(json_encode($json, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }
    if (strpos($cfg, '#') !== false) return preg_replace('/#.*/', '#' . CFG_NAME, $cfg);
    return $cfg . '#' . CFG_NAME;
}
function renameJsonConfig($jsonRaw) {
    $decoded = json_decode($jsonRaw, true);
    if (!is_array($decoded)) return $jsonRaw;
    $decoded['remarks'] = CFG_NAME;
    if (isset($decoded['outbounds']) && is_array($decoded['outbounds'])) {
        foreach ($decoded['outbounds'] as &$ob) {
            if (is_array($ob)) $ob['tag'] = CFG_NAME;
        }
    }
    return json_encode($decoded, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

// ================= Validators =================
function validate_vless_like($url) {
    $p = @parse_url($url);
    if (!$p || strtolower($p['scheme'] ?? '') !== 'vless') return false;
    if (empty($p['user']) || empty($p['host']) || empty($p['port'])) return false;
    if (!is_uuid($p['user'])) return false;
    if (!is_host_like($p['host'])) return false;
    if (!is_port($p['port'])) return false;
    return true;
}
function validate_trojan($url) {
    $p = @parse_url($url);
    if (!$p || strtolower($p['scheme'] ?? '') !== 'trojan') return false;
    if (empty($p['user']) || empty($p['host']) || empty($p['port'])) return false;
    if (!is_host_like($p['host']) || !is_port($p['port'])) return false;
    if (strlen($p['user']) < 4) return false;
    return true;
}
function validate_vmess($url) {
    if (stripos($url, 'vmess://') !== 0) return false;
    $b64 = base64url_to_base64(trim(substr($url, 8)));
    $dec = base64_decode($b64, true);
    if ($dec === false) return false;
    $j = json_decode($dec, true);
    if (!is_array($j)) return false;
    if (empty($j['add']) || empty($j['port']) || empty($j['id'])) return false;
    if (!is_host_like((string)$j['add'])) return false;
    if (!is_port((string)$j['port'])) return false;
    if (!is_uuid((string)$j['id'])) return false;
    return true;
}
function validate_ss($url) {
    if (stripos($url, 'ss://') !== 0) return false;
    $rest = substr($url, 5);
    $rest = preg_split('/[?#]/', $rest, 2)[0];
    if ($rest === '') return false;

    // حالت method:pass@host:port
    $rest1 = safe_urldecode_once($rest);
    if (strpos($rest1, '@') !== false) {
        $p = @parse_url('ss://' . $rest1);
        if ($p && !empty($p['user']) && !empty($p['pass']) && !empty($p['host']) && !empty($p['port'])) {
            if (!is_host_like($p['host']) || !is_port($p['port'])) return false;
            if (strlen($p['user']) < 2 || strlen($p['pass']) < 2) return false;
            return true;
        }
    }

    // حالت base64
    $parts = explode('@', $rest, 2);
    $b64part = base64url_to_base64($parts[0]);
    $dec = base64_decode($b64part, true);
    if ($dec === false) return false;
    if (!preg_match('/^[A-Za-z0-9._-]+:.+$/', $dec)) return false;

    if (isset($parts[1])) {
        $hp = preg_split('/[?#]/', $parts[1], 2)[0];
        if (!preg_match('/^(\[[0-9a-f:]+\]|[^:]+):(\d{1,5})$/i', $hp, $m)) return false;
        if (!is_host_like($m[1]) || !is_port($m[2])) return false;
    }
    return true;
}
function validate_hysteria($url) {
    $scheme = strtolower(parse_url($url, PHP_URL_SCHEME) ?? '');
    if ($scheme !== 'hysteria') return false;
    $p = @parse_url($url);
    if (!$p || empty($p['host']) || empty($p['port'])) return false;
    return is_host_like($p['host']) && is_port($p['port']);
}
function validate_hy2($url) {
    $scheme = strtolower(parse_url($url, PHP_URL_SCHEME) ?? '');
    if ($scheme !== 'hy2') return false;
    $p = @parse_url($url);
    if (!$p || empty($p['host']) || empty($p['port'])) return false;
    return is_host_like($p['host']) && is_port($p['port']);
}
function validate_wg($url) {
    $scheme = strtolower(parse_url($url, PHP_URL_SCHEME) ?? '');
    if ($scheme !== 'wg' && $scheme !== 'wireguard') return false;
    return (bool)preg_match('/^(wg|wireguard):\/\/\S{6,}$/i', $url);
}
function validate_by_scheme($url) {
    $scheme = strtolower(parse_url($url, PHP_URL_SCHEME) ?? '');
    return match ($scheme) {
        'vless' => validate_vless_like($url),
        'vmess' => validate_vmess($url),
        'trojan' => validate_trojan($url),
        'ss' => validate_ss($url),
        'ssr' => true,
        'hysteria' => validate_hysteria($url),
        'hy2' => validate_hy2($url),
        'wg', 'wireguard' => validate_wg($url),
        default => false,
    };
}

// ================= Extractors =================
function extractLinkTokensPrecise($text) {
    $out = [];
    $re = '/(?<![A-Za-z0-9_])(?P<scheme>vless|vmess|trojan|ssr|ss|wg|wireguard|hysteria|hy2):\/\/(?P<body>[^\s<>"\'`]+)/i';
    if (preg_match_all($re, $text, $m, PREG_SET_ORDER)) {
        foreach ($m as $one) {
            $scheme = strtolower($one['scheme']);
            $full = $scheme . '://' . $one['body'];
            $full = rtrim($full, " \t\r\n)];,.!?>");
            if (strlen($full) < 10) continue;
            $out[] = $full;
        }
    }
    return array_values(array_unique($out));
}

function isV2rayNgFullConfig($decoded) {
    if (!is_array($decoded)) return false;
    $isAssoc = array_keys($decoded) !== range(0, count($decoded) - 1);
    if (!$isAssoc) return false;

    if (!isset($decoded['outbounds']) || !is_array($decoded['outbounds']) || count($decoded['outbounds']) < 1) return false;

    $hasValidOutbound = false;
    foreach ($decoded['outbounds'] as $ob) {
        if (!is_array($ob)) continue;
        $p = strtolower((string)($ob['protocol'] ?? ''));
        if ($p === '') continue;
        if (in_array($p, [
            'vless','vmess','trojan','shadowsocks','ss','ssr','hysteria','hy2',
            'socks','http','wireguard','freedom','blackhole','dns','loopback'
        ], true)) { $hasValidOutbound = true; break; }
    }
    if (!$hasValidOutbound) return false;

    $hasCore = (
        (isset($decoded['inbounds']) && is_array($decoded['inbounds']) && count($decoded['inbounds']) > 0) ||
        isset($decoded['routing']) || isset($decoded['dns']) || isset($decoded['log']) ||
        isset($decoded['policy']) || isset($decoded['api']) || isset($decoded['stats'])
    );

    return $hasCore;
}

function extractJsonConfigsRawFull($text) {
    $results = [];
    $len = strlen($text);
    $i = 0;

    while ($i < $len) {
        $ch = $text[$i];
        if ($ch === '{' || $ch === '[') {
            $start = $i;
            $depth = 0;
            $inString = false;
            $escape = false;

            for (; $i < $len; $i++) {
                $c = $text[$i];

                if ($inString) {
                    if ($escape) $escape = false;
                    else {
                        if ($c === '\\') $escape = true;
                        elseif ($c === '"') $inString = false;
                    }
                } else {
                    if ($c === '"') $inString = true;
                    elseif ($c === '{' || $c === '[') $depth++;
                    elseif ($c === '}' || $c === ']') {
                        $depth--;
                        if ($depth === 0) {
                            $jsonStr = substr($text, $start, $i - $start + 1);
                            $decoded = json_decode($jsonStr, true);
                            if ($decoded !== null && json_last_error() === JSON_ERROR_NONE) {
                                $ok = false;
                                if (isV2rayNgFullConfig($decoded)) $ok = true;
                                else if (is_array($decoded) && array_keys($decoded) === range(0, count($decoded) - 1)) {
                                    foreach ($decoded as $item) {
                                        if (isV2rayNgFullConfig($item)) { $ok = true; break; }
                                    }
                                }
                                if ($ok) $results[] = $jsonStr;
                            }
                            break;
                        }
                    }
                }
            }
        }
        $i++;
    }

    return array_values(array_unique($results));
}

// ================= Collect + Dedupe =================
$configs = [];

// لینک‌ها
foreach (extractLinkTokensPrecise($response) as $u) {
    if (!validate_by_scheme($u)) continue;
    $configs[] = renameLinkConfig($u);
}

// JSONها
foreach (extractJsonConfigsRawFull($response) as $rawJson) {
    $configs[] = renameJsonConfig($rawJson);
}

if (empty($configs)) {
    header('Content-Type: text/plain; charset=UTF-8');
    die("هیچ کانفیگ معتبر پیدا نشد");
}

// ددیوپ نهایی (بدون تغییر محتوا): با hash
$unique = [];
foreach ($configs as $c) {
    $h = hash('sha256', $c);
    $unique[$h] = $c;
}
$configs = array_values($unique);

// ================= OUTPUT: ONLY ONE (equal probability) =================
$selected = $configs[random_int(0, count($configs) - 1)];

header('Content-Type: text/plain; charset=UTF-8');
echo $selected;