#!/usr/bin/env php
<?php
/**
 * Assert customer-facing message templates do not contain raw proxy config schemes.
 *
 * Usage: php scripts/assert-no-raw-configs.php
 */
if (php_sapi_name() !== 'cli') {
    exit(1);
}

require_once dirname(__DIR__) . '/services/SubscriptionDelivery.php';

$root = dirname(__DIR__);
$files = [
    $root . '/settings/values.php',
    $root . '/services/SubscriptionDelivery.php',
    $root . '/config.php',
];

$patterns = ['vless://', 'vmess://', 'trojan://', 'ss://', 'hysteria://', 'hy2://'];
$failed = 0;

foreach ($files as $file) {
    if (!file_exists($file)) {
        continue;
    }
    $content = file_get_contents($file);
    $lines = explode("\n", $content);
    foreach ($lines as $num => $line) {
        if (strpos($line, 'getConnectionLink') !== false) {
            continue;
        }
        if (strpos($line, 'getClientLinks') !== false || strpos($line, 'subLinks') !== false) {
            continue;
        }
        if (preg_match('/customer|acc_text|formatCustomer|sent_config|renewed_config|subscription/i', $line)) {
            foreach ($patterns as $p) {
                if (stripos($line, $p) !== false) {
                    echo "[FAIL] {$file}:" . ($num + 1) . " contains $p\n";
                    $failed++;
                }
            }
        }
    }
}

$sample = SubscriptionDelivery::formatCustomerMessage('test', 'https://sub.example.com/sub/abc123');
if (SubscriptionDelivery::containsRawConfig($sample)) {
    echo "[FAIL] formatCustomerMessage produced raw config pattern\n";
    $failed++;
} else {
    echo "[PASS] formatCustomerMessage is clean\n";
}

$bad = "Your config: vless://uuid@host:443";
if (!SubscriptionDelivery::containsRawConfig($bad)) {
    echo "[FAIL] containsRawConfig should detect vless://\n";
    $failed++;
} else {
    echo "[PASS] containsRawConfig detects raw schemes\n";
}

echo $failed === 0 ? "\nAll assertions passed.\n" : "\n$failed assertion(s) failed.\n";
exit($failed > 0 ? 1 : 0);
