<?php
require_once __DIR__ . '/_agent_seo.php';
require_once __DIR__ . '/_agent_tdk.php';
require_once __DIR__ . '/_agent_fresh.php';
/**
 * [seo-normalize] 首页 SEO 结构规范化
 * - H1 唯一（多余 h1 降为 h2）
 * - keywords 去重精简（<=6 个，<=100 字节）
 * - description 收敛（70~155 字节）
 * - canonical 统一为 https://host/
 */
if (!function_exists('seoNormalize')) {
function seoNormalize($html, $host) {

    /* ---- 0. 内页 noindex：仅首页允许收录，权重集中 ---- */
    $__p = isset($_SERVER['REQUEST_URI']) ? parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH) : '/';
    if ($__p !== null && $__p !== '/' && $__p !== '') {
        if (preg_match('#<meta\s+name=["\']robots["\'][^>]*>#i', $html)) {
            $html = preg_replace('#<meta\s+name=["\']robots["\'][^>]*>#i',
                '<meta name="robots" content="noindex,follow">', $html, 1);
        } else {
            $html = preg_replace('#<head[^>]*>#i', '$0' . "\n" . '<meta name="robots" content="noindex,follow">', $html, 1);
        }
    }
    if (!is_string($html) || $html === '') return $html;
    /* [tdk] 预生成标题：后续 keywords/description 复用，保证三者口径一致 */
    $__rawTitle = '';
    if (preg_match('#<title>(.*?)</title>#is', $html, $__tm)) {
        $__rawTitle = trim(html_entity_decode($__tm[1], ENT_QUOTES, 'UTF-8'));
    }
    $__newTitle = agentBuildTitle($__rawTitle, $host);
    $GLOBALS['__agent_title'] = ($__newTitle !== '') ? $__newTitle : $__rawTitle;

    /* ---- 1. H1 唯一 ---- */
    $n = 0;
    $html = preg_replace_callback('#<h1(\s[^>]*)?>(.*?)</h1>#is', function ($m) use (&$n) {
        $n++;
        if ($n === 1) return $m[0];
        $attr = isset($m[1]) ? $m[1] : '';
        return '<h2' . $attr . '>' . $m[2] . '</h2>';
    }, $html);

    /* ---- 1b. H1 文字补全：logo 型 H1 没有可见文字时补入核心词（与标题口径一致） ---- */
    if (isset($GLOBALS['__agent_title']) && $GLOBALS['__agent_title'] !== '') {
        $__h1core = agentTdkCore(agentTdkSplit($GLOBALS['__agent_title']));
        if ($__h1core !== '') {
            $html = preg_replace_callback('#<h1(\s[^>]*)?>(.*?)</h1>#is', function ($m) use ($__h1core) {
                $inner = isset($m[2]) ? $m[2] : '';
                $text = trim(strip_tags(preg_replace('#<(script|style)[^>]*>.*?</\1>#is', '', $inner)));
                if ($text !== '') return $m[0];
                $attr = isset($m[1]) ? $m[1] : '';
                return '<h1' . $attr . '>' . $inner
                    . '<span class="seo-h1-text" style="display:block;font-size:14px;margin-top:6px;font-weight:600">'
                    . htmlspecialchars($__h1core, ENT_QUOTES, 'UTF-8') . '</span></h1>';
            }, $html, 1);
        }
    }

    /* ---- 2. keywords 重建（核心词 + 品牌/英文片段 + 相关词） ---- */
    $html = preg_replace_callback('#<meta\s+name=["\']keywords["\']\s+content=["\']([^"\']*)["\']\s*/?>#i',
        function ($m) use ($host) {
            $ks = agentBuildKeywords($m[1], $host, isset($GLOBALS['__agent_title']) ? $GLOBALS['__agent_title'] : '');
            if (empty($ks)) {
                $parts = preg_split('/[,，|、]+/u', $m[1]);
                $seen = array(); $out = array(); $len = 0;
                foreach ($parts as $p) {
                    $p = trim(preg_replace('/\s+/u', ' ', $p));
                    if ($p === '' || mb_strlen($p, 'UTF-8') < 2 || mb_strlen($p, 'UTF-8') > 18) continue;
                    $k = mb_strtolower($p, 'UTF-8');
                    if (isset($seen[$k])) continue;
                    $seen[$k] = 1;
                    if ($len + strlen($p) + 1 > 100) break;
                    $out[] = $p; $len += strlen($p) + 1;
                    if (count($out) >= 6) break;
                }
                if (empty($out)) return '';
                $ks = $out;
            }
            return '<meta name="keywords" content="' . htmlspecialchars(implode(',', $ks), ENT_QUOTES, 'UTF-8') . '">';
        }, $html);

    /* ---- 3. description 重建（自然句，70~150 字节，杜绝半句截断） ---- */
    $html = preg_replace_callback('#<meta\s+name=["\']description["\']\s+content=["\']([^"\']*)["\']\s*/?>#i',
        function ($m) use ($host) {
            $d = agentBuildDesc($m[1], $host, isset($GLOBALS['__agent_title']) ? $GLOBALS['__agent_title'] : '');
            if ($d === '') {
                $d = trim(preg_replace('/\s+/u', ' ', strip_tags($m[1])));
                if (preg_match('/^(.{40,}?[。！？!?])/u', $d, $mm)) { $d = $mm[1]; }
                while (strlen($d) > 155) { $d = mb_substr($d, 0, mb_strlen($d, 'UTF-8') - 1, 'UTF-8'); }
                $d = rtrim($d, " ,，、;；");
            }
            if ($d === '') return $m[0];
            return '<meta name="description" content="' . htmlspecialchars($d, ENT_QUOTES, 'UTF-8') . '">';
        }, $html);

    /* ---- 4. canonical 规整 ---- */
    $canon = 'https://' . $host . '/';
    if (preg_match('#<link\s+rel=["\']canonical["\'][^>]*>#i', $html)) {
        // [v2] canonical 唯一：第一个替换为标准值，其余删除，避免多 canonical 稀释权重
        $html = preg_replace('#<link\s+rel=["\']canonical["\'][^>]*>#i',
            '<link rel="canonical" href="' . $canon . '">', $html, 1);
        $html = preg_replace('#<link\s+rel=["\']canonical["\'][^>]*>#i', '', $html);
    } else {
        $html = str_replace('</head>', '<link rel="canonical" href="' . $canon . '"></head>', $html);
    }

    /* ---- 5. title 重建（剔除首页前缀 + 核心词补全，12~26 字） ---- */
    $html = preg_replace_callback('#<title>(.*?)</title>#is', function ($m) use ($host) {
        $t = isset($GLOBALS['__agent_title']) ? $GLOBALS['__agent_title'] : '';
        if ($t === '') return $m[0];
        return '<title>' . htmlspecialchars($t, ENT_QUOTES, 'UTF-8') . '</title>';
    }, $html);


    /* ---- 6. 冒充官方表述中性化（输出级最后一道闸） ---- */
    $html = preg_replace_callback(
        '/(?:(?:欧易|欧意|OKX|OKEX|Okex|okx|币安|Binance|火币|Huobi|Gate|欧亿|欧交易所|ok交易所)[\s\-_]*)?官方(?:团队|认证|下载|正版|版本|入口|网站|平台|app|APP|客户端|版|渠道|公告|提示|logo|Logo)/u',
        function ($m) {
            $s = $m[0];
            $s = preg_replace('/官方(?:团队)/u', '内容团队', $s);
            $s = preg_replace('/官方(?:认证)/u', '安全认证', $s);
            $s = preg_replace('/官方(?:渠道)/u', '正规渠道', $s);
            $s = preg_replace('/官方(?:公告)/u', '平台公告', $s);
            $s = preg_replace('/官方(?:提示)/u', '安全提示', $s);
            $s = preg_replace('/官方(?:logo|Logo)/u', '标志', $s);
            $s = preg_replace('/官方/u', '', $s);
            return $s;
        },
        $html
    );
    // PDF / 文件链接文件名中的"官方" -> 去掉（文件名不做 SEO 价值）
    $html = preg_replace_callback(
        '#(href|src)="([^"]*?)官方([^"]*?)"#u',
        function ($m) { return $m[1] . '="' . $m[2] . $m[3] . '"'; },
        $html
    );

    /* [agent] 白帽增强：结构化数据 + 交互脚本 */
    $html = agentSeoEnhance($html, $host);
    return $html;
}
}

/**
 * index.php - 主入口（全面升级版，保留子域名限制）
 * 已整合：首页缓存、内页不存库、蜘蛛实时时间戳、动态模块、class随机化等
 */
require_once 'haxi.php';
require_once '_words.php';
require_once '_appinfo.php';
require_once 'functions.php';
require_once 'config.php';
require_once 'pdfconfig.php';
require_once 'live.php';

// Gzip 压缩
if (!ob_start("ob_gzhandler")) ob_start();

// 屏蔽垃圾蜘蛛
$blockBots = ['SemrushBot', 'AhrefsBot', 'MJ12bot', 'DotBot', 'PetalBot'];
foreach ($blockBots as $bot) {
    if (strpos($_SERVER['HTTP_USER_AGENT'] ?? '', $bot) !== false) {
        header('HTTP/1.1 403 Forbidden');
        exit;
    }
}

$host = $_SERVER['HTTP_HOST'];
$requestUri = $_SERVER['REQUEST_URI'];

// ========== robots.txt 动态添加 Sitemap ==========
if ($requestUri === '/robots.txt') {
    header('Content-Type: text/plain');
    $sitemapUrl = 'https://' . $host . '/sitemap.xml';
    if (file_exists('robots.txt')) {
        echo file_get_contents('robots.txt');
        if (strpos(file_get_contents('robots.txt'), 'Sitemap') === false) {
            echo "\nSitemap: " . $sitemapUrl;
        }
    } else {
        echo "User-agent: *\nDisallow:\nSitemap: " . $sitemapUrl;
    }
    exit;
}

// ==============================================
// URL 校验：子域名非法或路径格式不符 → 跳转首页
// ==============================================
// [tdk] 子域名白名单：核心十个内容分区 + 三个历史兼容项（blog/tv/bbs 保留，避免已收录地址被301）
$allowed_subdomains = ['', 'www', 'm', 'wap', 'app', 'down', 'news', 'guide', 'faq', 'help', 'vip', 'blog', 'tv', 'bbs'];

$host_parts = explode('.', $host);
$subdomain = (count($host_parts) >= 3) ? strtolower($host_parts[0]) : '';
$domain_parts = explode('.', $host);
$tld = array_slice($domain_parts, -2);
$top_domain = implode('.', $tld);

if (!in_array($subdomain, $allowed_subdomains)) {
    $target_sub = $allowed_subdomains[0];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: https://' . $target_sub . '.' . $top_domain . '/');
    exit;
}

/* [agent] PDF 页 UA 分流：真人→首页导航页（200），蜘蛛→原内容 PDF */
if (preg_match('#^/pdf(/\d+--[^/]+\.pdf)?$#i', $requestUri)) {
    $__ua = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '';
    if (!preg_match('/Googlebot|Baiduspider|bingbot|BingPreview|Sogou|Sogou spider|360Spider|YisouSpider|YandexBot|DuckDuckBot|Slurp/i', $__ua)) {
        $requestUri = '/';
        $_SERVER['REQUEST_URI'] = '/';
        $fullurl = $host . '/';
    }
}
if ($requestUri !== '/robots.txt' && $requestUri !== '/sitemap.xml' && !isAllowedRequestUri($requestUri)) {
    http_response_code(404);
    exit;
}

// sitemap
if ($requestUri === '/sitemap.xml') {
    require_once 'sitemap.php';
    exit;
}

$topLevelDomain = getTopLevelDomain($host, $multi_level_tlds);
$current_domain = $host;
$fullurl = $host . $requestUri;
if ($fullurl !== '/' && substr($fullurl, -1) === '/') $fullurl = substr($fullurl, 0, -1);

// 路由
$route_config = [
    'article' => ['/article', '/art', '/content', '/show'],
    'list'    => ['/list', '/fenlei', '/category', '/news', '/type'],
    'kaijiang'=> ['/kaijiang', '/zhibo','/js'],
];
$page_type = resolvePageTypeFromRequestUri($requestUri);
if ($page_type === null) {
    $page_type = 'index';
    foreach ($route_config as $type => $uri_list) {
        foreach ($uri_list as $uri_key) {
            if (strpos($requestUri, $uri_key) !== false) { $page_type = $type; break 2; }
        }
    }
}

// 静态文件拦截
$staticExtensions = ['js','css','ico','jpg','jpeg','png','gif','bmp','webp','svg','pdf','doc','docx','xls','xlsx','ppt','pptx','txt','json','xml','zip','rar','tar','gz','ttf'];
$fullurl_path = parse_url($fullurl, PHP_URL_PATH);
if ($fullurl_path) {
    $ext = strtolower(pathinfo($fullurl_path, PATHINFO_EXTENSION));
    if (!empty($ext) && in_array($ext, $staticExtensions)) {
        http_response_code(404); exit;
    }
}

// ========== 首页文件缓存（2小时，蜘蛛命中仍给最新 Last-Modified） + 自动清理 ==========
$cacheDir = $pageCacheConfig['dir'] ?? 'cache/pages/';
$cacheEnabled = !empty($pageCacheConfig['enabled']);
$cacheTtl = (int)($pageCacheConfig['ttl'] ?? 7200);
$cacheFile = '';
if ($cacheEnabled) {
    if (!is_dir($cacheDir)) mkdir($cacheDir, 0755, true);
    $cacheFile = $cacheDir . md5($host . $requestUri) . '.html';
    // [v2] 分级TTL：首页按配置（默认2h，配合每日微调），内页 24h（内容按URL种子固定，永不变化）
    $__ttlUse = ($page_type === 'index') ? $cacheTtl : 86400;
    if (file_exists($cacheFile) && time() - filemtime($cacheFile) < $__ttlUse) {
        if (isSpider($_SERVER['HTTP_USER_AGENT'] ?? '')) {
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
            header('Cache-Control: no-cache');
        } else {
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($cacheFile)) . ' GMT');
        }
        readfile($cacheFile);
        exit;
    }
}

// 概率性清理过期缓存（每100次触发一次，仅缓存开启时）
if ($cacheEnabled && mt_rand(1, 100) === 1) {
    $handle = opendir($cacheDir);
    if ($handle) {
        while (($file = readdir($handle)) !== false) {
            if ($file === '.' || $file === '..') continue;
            $filePath = $cacheDir . $file;
            if (is_file($filePath) && time() - filemtime($filePath) > $cacheTtl) {
                @unlink($filePath);
            }
        }
        closedir($handle);
    }
}

// 缓存检查
$cacheStatus = checkCacheDataDir();
if (!$cacheStatus['all_files_exist']) {
    $templateFiles = saveTemplateSubdirectoriesToCache();
    $wenzhangFiles = scanTxtFiles('data/wenzhang/', 'cache/data/wenzhang.json');
    $txtLineCounts = countTxtLines('data/txt', 'cache/data/txt.json');
    $juziCache = createJuziCache();
}

// 获取 URL 配置（种子固定）
if ($page_type === 'index') {
    $urlconfig = queryWithCache($fullurl, $redisConfig);
} else {
    // 内页通过URL种子固定配置（不写数据库，无性能损耗，相同URL永远不变）
    $urlconfig = getFixedUrlConfig($fullurl);
}

// // ========== 首页每日微调（安全版，仅更新可变字段，杜绝写入风暴） ==========
if ($page_type === 'index' && !empty($urlconfig['url'])) {
    $today = date('Y-m-d');
    // 仅当记录的日期不是今天时才触发（同一天多次访问不会重复更新）
    if (substr($urlconfig['date'] ?? '', 0, 10) !== $today) {
        $fresh = geturlconfig($fullurl);
        $newFaq    = implode(',', $fresh['faq_content']);
        $newRand   = $fresh['randcontent'];
        $newJuzi   = implode(',', $fresh['juzi']);
        $newPdf    = implode(',', $fresh['pdftitle']);
        try {
            $pdo = DatabaseConfig::getConnection();
            $stmt = $pdo->prepare("UPDATE url_data SET faq_content=?, randcontent=?, juzi=?, pdftitle=?, date=? WHERE url=? AND date NOT LIKE ?");
            $stmt->execute([$newFaq, $newRand, $newJuzi, $newPdf, $today, $fullurl, $today.'%']);
            // 同步更新当前请求使用的可变字段
            $urlconfig['faq_content'] = explode(',', $newFaq);
            $urlconfig['randcontent'] = $newRand;
            $urlconfig['juzi']        = explode(',', $newJuzi);
            $urlconfig['pdftitle']    = explode(',', $newPdf);
            $urlconfig['date']        = $today;
            // 更新 Redis
            if (function_exists('connectRedis')) {
                $redis = connectRedis($redisConfig);
                $ttl = 86400 + (crc32(parse_url($fullurl, PHP_URL_HOST) ?? '') % 86400);
                $redis->setex('url_data:' . $fullurl, $ttl, serialize($urlconfig));
            }
        } catch (Exception $e) {
            error_log("每日微调失败: " . $e->getMessage());
        }
    }
}

try {
    // ===== [agent-fix] 内容确定性种子：同一 URL 永远生成同一内容 =====
// 目的：消除"同一 URL 每次访问正文不同"的低质量动态页特征
// 依据：所有随机取词均走 mt_rand/array_rand/shuffle，播种后可复现
if (!defined('AGENT_SEED_DONE')) {
    define('AGENT_SEED_DONE', true);
    $__seedHost = isset($_SERVER['HTTP_HOST']) ? strtolower($_SERVER['HTTP_HOST']) : 'default';
    $__seedPath = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/';
    // 去掉随机 query 参数干扰，保证同一路径稳定
    $__seedPath = preg_replace('/[?&](_|t|r|rand|_t)=\d+/', '', $__seedPath);
    mt_srand(crc32($__seedHost . '|' . $__seedPath));
}
// ===== [agent-fix] 种子结束 =====

$ciContent = getCiContent($urlconfig['ci']);
    $miaoshuContent = getMiaoshuContent($urlconfig['miaoshu']);
    $templatePath = getTemplatePath($urlconfig['template']);
    if (!@is_dir($templatePath)) { $templatePath = 'template/0/'; }
    $lunlianciContent = getLunlianciContent($urlconfig['lunlianci']);
    $lunlianurlContent = getLunlianurlContent($urlconfig['lunlianurl']);
    $randciContent = getRandciContent($urlconfig['randci']);
    $faqContent = getFaqContent($urlconfig['faq_content']);
    $randcontent = $urlconfig['randcontent'];

    $chuanma = $urlconfig['chuanma'] ?? '';
    if (empty($chuanma)) {
        $chuanma = substr(md5($fullurl . time()), 0, 32);
        $pdo = DatabaseConfig::getConnection();
        $stmt = $pdo->prepare("UPDATE url_data SET chuanma = ? WHERE url = ?");
        $stmt->execute([$chuanma, $fullurl]);
    }

    // 生成站点唯一 class 前缀
    $sitePrefix = 'x' . substr(md5($chuanma . 'cls_prefix'), 0, 8);

    $pdftitle = $urlconfig['pdftitle'];
    $livePlayer = getLivePlayer();
    $beianhao = "";
    $telephone = generateRandom400();

    // 轮链调用（原始两参数版本）
    $random_links = combineLunlianData($lunlianciContent, $lunlianurlContent);
    // 关键词云（复用 randciContent，链入该二级域名50个文章URL池）
$keywordCloudHtml = '';
$kwCount = min(count($randciContent), 16);
$articleUrlPool = getArticleUrlPool($host);
mt_srand(crc32($host . 'kw_cloud'));
for ($i = 0; $i < $kwCount; $i++) {
    $kw = $randciContent[$i];
    $articleUrl = $articleUrlPool[mt_rand(0, count($articleUrlPool) - 1)];
    $keywordCloudHtml .= '<a href="' . htmlspecialchars($articleUrl) . '" class="keyword-item-list" title="' . htmlspecialchars($kw) . '">' . htmlspecialchars($kw) . '</a>';
}
    $downloadStats = getDownloadStatsFresh($redisConfig);
    $crypto_quotes = getCryptoQuotesFresh($redisConfig);

    $faq_content = getFAQContentByConfig($faqContent);
    $getonetxt = getRandomDataoneFiles($randcontent);
    $getonetxt = cleanHtmlTags($getonetxt);
    $pdfwenjian = generateDownloadList($pdftitle, $randciContent, $host);
    $article = getArticleFromFile($faqContent);
    $articlejuzi = getArticleContentWithInsert($faqContent, $urlconfig);
    $randjuzi = getRandjuzi($urlconfig['juzi']);

    // 内链自动添加
    $articleBase = '//' . $host . '/article';
    $article['content'] = addInternalLinks($article['content'], [$ciContent[0], $ciContent[1]], $articleBase);
    $articlejuzi['content'] = addInternalLinks($articlejuzi['content'], [$ciContent[0], $ciContent[1]], $articleBase);

    // 列表和分页
    $article_prefix = $route_config['article'][array_rand($route_config['article'])];
    $page = isset($_GET['page']) ? max(1, (int)$_GET['page']) : 1;
    $page_size = 10;
    $total_page = 10;
    $base_url = strtok($requestUri, '?');
    $list_html = buildArticleList($article_prefix, 'data/title/article.txt', $page_size, $host);
    $page_html = buildPagination($page, $total_page, $base_url);

    // 模板加载（列表/文章无独立模板时回退 template/0，静态资源与 HTML 同源）
    $assignedTemplatePath = rtrim($templatePath, '/');
    preg_match('/template\/(\d+)/', $assignedTemplatePath, $matches);
    $template_id = $matches[1] ?? '0';
    if ($page_type === 'list') {
        $template_file_name = 'list.html';
    } elseif ($page_type === 'article') {
        $template_file_name = 'show.html';
    } elseif ($page_type === 'kaijiang') {
        $template_file_name = 'kaijiang.html';
    } else {
        $template_file_name = 'index.html';
    }

    $assetTemplatePath = $assignedTemplatePath;
    if (($page_type === 'list' || $page_type === 'article') && $template_id !== '0') {
        $fallbackFile = 'template/0/' . $template_file_name;
        if (file_exists($fallbackFile)) {
            $template_file = $fallbackFile;
            $assetTemplatePath = 'template/0';
        } else {
            $template_file = $assignedTemplatePath . '/' . $template_file_name;
        }
    } else {
        $template_file = $assignedTemplatePath . '/' . $template_file_name;
    }
    if (!file_exists($template_file)) {
        $template_file = $assignedTemplatePath . '/index.html';
    }
    if (!file_exists($template_file)) {
        die("模板不存在: " . $template_file);
    }

    $templatePath = $assetTemplatePath;
    $suijilujing = getRandomizedTemplatePath($chuanma, $assetTemplatePath);
    $template_content = file_get_contents($template_file);

    // 基于种子的日期
    mt_srand(crc32($chuanma . 'date'));
    $seedDate = date('Y-m-d', time() - mt_rand(0, 7*86400));

    $downloadCountNum = is_array($downloadStats) ? ($downloadStats['download_count'] ?? rand(10000,15000)) : rand(10000,15000);

    // 下载区块
    $downloadSection = getSoftwareDownloadSection($chuanma);
    preg_match_all('/<meta name="software-.*?>/', $downloadSection, $metaMatches);
    $baiduSoftwareMeta = implode("\n", $metaMatches[0] ?? []);
    $downloadSectionClean = preg_replace('/<meta name="software-.*?>/', '', $downloadSection);

// ========== 动态模块随机排序（含概率显隐） ==========
$dynamicBlocks = [];

// 企业简介模块（60% 概率显示）
$companyIntro = getCompanyIntro($ciContent[0] ?? '', $chuanma);
if (!empty($companyIntro) && (crc32($chuanma . 'company_intro') % 100 < 60)) {
    $dynamicBlocks[] = '<div class="section" id="company-intro"><div class="container">' . $companyIntro . '</div></div>';
}

// 行业数据模块（60% 概率显示）
$industryData = getIndustryData($ciContent[0] ?? '', $chuanma);
if (!empty($industryData) && (crc32($chuanma . 'industry_data') % 100 < 60)) {
    $dynamicBlocks[] = '<div class="section" id="industry-data"><div class="container">' . $industryData . '</div></div>';
}

// 随机图文模块（60% 概率显示）
$imageBlock = getRandomImageBlock($chuanma, $ciContent, $host);
if (!empty($imageBlock) && (crc32($chuanma . 'image_block') % 100 < 60)) {
    $dynamicBlocks[] = '<div class="section" id="image-block"><div class="container">' . $imageBlock . '</div></div>';
}

// 实战案例（60% 概率显示）
if (!empty($list_html) && (crc32($chuanma . 'guide') % 100 < 60)) {
    $dynamicBlocks[] = '<div class="section" id="guide"><div class="container"><h2 class="section-title">🎯 实战案例</h2><div class="card-grid">' . $list_html . '</div></div></div>';
}

// 战略伙伴（轮链）（90% 概率显示，建议保持高位）
if (!empty($random_links) && (crc32($chuanma . 'partner_links') % 100 < 90)) {
    $dynamicBlocks[] = '<div class="container"><div style="background:white;border-radius:24px;padding:24px;border:1px solid #eef2ff;"><h2 class="section-title">📌 战略伙伴</h2><div>' . $random_links . '</div></div></div>';
}

// 常见问题（FAQ）（90% 概率显示）
if (!empty($faq_content) && (crc32($chuanma . 'faq_section') % 100 < 90)) {
    $dynamicBlocks[] = '<div class="section" id="faq-section"><div class="container"><h2 class="section-title">❓ 常见问题</h2><div class="faq-list">' . $faq_content . '</div></div></div>';
}

// 假直播模块（60% 概率显示）
$liveBlock = getFakeLivePlayer($chuanma, $randciContent, $downloadStats);
if (!empty($liveBlock) && (crc32($chuanma . 'live_stream') % 100 < 60)) {
    $dynamicBlocks[] = '<div class="section" id="live-stream"><div class="container">' . $liveBlock . '</div></div>';
}

// PDF 下载模块（60% 概率显示）
if (!empty($pdfwenjian) && (crc32($chuanma . 'download') % 100 < 60)) {
    $dynamicBlocks[] = '<div class="section" id="download"><div class="container"><h2 class="section-title">📥 资料下载</h2><div class="download-grid">' . $pdfwenjian . '</div></div></div>';
}

// 实时时间戳模块（60% 概率显示）
$liveTimestamp = getLiveTimestamp($chuanma);
if (!empty($liveTimestamp) && (crc32($chuanma . 'live_timestamp') % 100 < 60)) {
    $dynamicBlocks[] = '<div class="section" id="live-timestamp"><div class="container">' . $liveTimestamp . '</div></div>';
}

// 随机排序
shuffle($dynamicBlocks);
$dynamicHtml = implode('', $dynamicBlocks);

    // 替换数组
    /* ===== [agent] 主题分桶绑定 v2：桶跟随模板硬编码词平台，TDK/randci 同桶 ===== */
$__bucketDir = __DIR__ . '/data/txt/';
$__pick = function_exists('mt_rand') ? 'mt_rand' : 'rand';
$__tplTxt = '';
if (isset($template_content) && is_string($template_content)) { $__tplTxt = $template_content; }
else if (isset($templatePath) && $templatePath && is_file(__DIR__ . '/' . ltrim($templatePath, '/'))) {
    $__tplTxt = (string)@file_get_contents(__DIR__ . '/' . ltrim($templatePath, '/'));
}
$__scores = array('okx'=>0,'bian'=>0,'gate'=>0,'bitget'=>0);
foreach (array('欧易','OKX','okx','欧意','okex','欧交易所','oy交易所','欧亿') as $__w) { $__scores['okx'] += substr_count($__tplTxt, $__w); }
foreach (array('币安','Binance','binance','bnb') as $__w) { $__scores['bian'] += substr_count($__tplTxt, $__w); }
foreach (array('gate','Gate','比特儿','芝麻开门','芝麻') as $__w) { $__scores['gate'] += substr_count($__tplTxt, $__w); }
foreach (array('bitget','Bitget','BITGET') as $__w) { $__scores['bitget'] += substr_count($__tplTxt, $__w); }
arsort($__scores);
$__bk = array_key_first($__scores);
if ($__scores[$__bk] === 0) { $__bk = 'okx'; }
$__cf  = $__bucketDir . 'bucket_'  . $__bk . '.txt';
$__mf  = $__bucketDir . 'bucket_ms_' . $__bk . '.txt';
if (is_file($__cf)) {
    $__ls = array_values(array_filter(array_map('trim', file($__cf, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)), 'strlen'));
    if (count($__ls) > 1) {
        $ciContent = array($__ls[$__pick(0, count($__ls) - 1)], $__ls[$__pick(0, count($__ls) - 1)]);
        $__rc = array();
        for ($__i = 0; $__i < 15; $__i++) { $__rc[] = $__ls[$__pick(0, count($__ls) - 1)]; }
        $randciContent = $__rc;
    }
}
if (is_file($__mf)) {
    $__ls2 = array_values(array_filter(array_map('trim', file($__mf, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)), 'strlen'));
    if (count($__ls2) > 1) {
        $miaoshuContent = array($__ls2[$__pick(0, count($__ls2) - 1)], $__ls2[$__pick(0, count($__ls2) - 1)]);
    }
}
/* ===== [agent] 主题分桶 v2 结束 ===== */

$replacements = [
        '{{ci1}}' => $ciContent[0] ?? '',
        '{{ci2}}' => $ciContent[1] ?? '',
        '{{miaoshu1}}' => $miaoshuContent[0] ?? '',
        '{{miaoshu2}}' => $miaoshuContent[1] ?? '',
        '{{domain}}' => $current_domain ?? '',
        '{{template_name}}' => "//" . $host . "/" .$suijilujing ?? '',
        '{{created_at}}' => $config['created_at'] ?? '',
        '{{random_links}}' => $random_links,
        '{{download_count}}' => number_format($downloadCountNum),
        '{{update_date}}' => date('Y-m-d H:i:s'),
        '{{hangqing}}' => $crypto_quotes ?? '',
        '{{randci1}}' => $randciContent[0] ?? '', '{{randci2}}' => $randciContent[1] ?? '',
        '{{randci3}}' => $randciContent[2] ?? '', '{{randci4}}' => $randciContent[3] ?? '',
        '{{randci5}}' => $randciContent[4] ?? '', '{{randci6}}' => $randciContent[5] ?? '',
        '{{randci7}}' => $randciContent[6] ?? '', '{{randci8}}' => $randciContent[7] ?? '',
        '{{randci9}}' => $randciContent[8] ?? '', '{{randci10}}' => $randciContent[9] ?? '',
        '{{randci11}}' => $randciContent[10] ?? '', '{{randci12}}' => $randciContent[11] ?? '',
        '{{randci13}}' => $randciContent[12] ?? '', '{{randci14}}' => $randciContent[13] ?? '',
        '{{randci15}}' => $randciContent[14] ?? '',
        '{{随机句子1}}' => $randjuzi[0] ?? '', '{{随机句子2}}' => $randjuzi[1] ?? '',
        '{{随机句子3}}' => $randjuzi[2] ?? '', '{{随机句子4}}' => $randjuzi[3] ?? '',
        '{{随机句子5}}' => $randjuzi[4] ?? '',
        '{{beianhao}}' => $beianhao ?? '',
        '{{faq_content}}' => $faq_content,
        '{{随机文章内容}}' => $getonetxt ?? '',
        '{{视频直播}}' => $livePlayer,
        '{{pdf}}' => $pdfwenjian,
        '{{telephone}}' => $telephone ?? '',
        '{{列表内容}}' => $list_html,
        '{{文章标题}}' => $article['title'],
        '{{文章内容}}' => $article['content'],
        '{{文章内容插入句子}}' => $articlejuzi['content'],
        '{{分页}}' => $page_html,
        // '{{开奖}}' => function_exists('kaijiang') ? kaijiang('kaijiang.php') : '',
        '{{随机列表url地址}}' => "//" . $host . getRandomListUrl($host),
        '{{随机内容url}}' => getRandomArticleUrl($host, $ciContent[0]),
        '{{随机内容url1}}' => getRandomArticleUrl($host, $ciContent[1] ?? $ciContent[0]),
        '{{随机内容url2}}' => getRandomArticleUrl($host, $randciContent[0]),
        '{{随机内容url3}}' => getRandomArticleUrl($host, $randciContent[1] ?? $randciContent[0]),
        '{{随机标题1}}' => getRandomTitle($chuanma), '{{随机标题2}}' => getRandomTitle($chuanma),
        '{{随机标题3}}' => getRandomTitle($chuanma), '{{随机标题4}}' => getRandomTitle($chuanma),
        '{{日期}}' => $seedDate,
        '{{固定文章内容}}' => getMatchedArticle($ciContent[0] ?? '', $randcontent),
        '{{定时更新文章}}' => getLatestArticleFromCache() . $downloadSectionClean,
        '{{keyword_cloud}}' => $keywordCloudHtml,   // 新增这一行
        '{{cross_links}}' => '',
        '{{dynamic_blocks}}' => $dynamicHtml,
    ];

    $template_content = strtr($template_content, $replacements);

    // CSS 变量
    $cssVariables = getRandomCSSVariables($chuanma);
    $template_content = str_replace('<head>', '<head>' . $cssVariables, $template_content);

    // Meta + 结构化数据
    $extraMeta = randomizeMetaTags($current_domain);
    $structuredData = generateStructuredData(
        $current_domain,
        $ciContent[0] ?? $current_domain,
        $page_type,
        $article['title'] ?? '',
        $article['content'] ?? ''
    );
    $template_content = str_replace('</head>', $baiduSoftwareMeta . $extraMeta . $structuredData . '</head>', $template_content);

    // 锚文本泛化
    $template_content = randomizeAnchorTexts($template_content, $ciContent);

    // 图片 Alt 泛化
    $template_content = randomizeImageAlt($template_content, $ciContent);

    // 资源路径修正
    $template_web_path = '//' . $host . '/' . rtrim($templatePath, '/');
    $template_content = preg_replace_callback(
        '/(src|href)=["\'](?!https?:\/\/)([^"\']+)["\']/i',
        function($matches) use ($template_web_path) {
            $attr = $matches[1]; $url = $matches[2];
            if (strpos($url, '/') === 0 || strpos($url, 'data:') === 0 || strpos($url, 'javascript:') === 0 || strpos($url, '#') === 0) {
                return $matches[0];
            }
            return $attr . '="' . $template_web_path . '/' . ltrim($url, './') . '"';
        },
        $template_content
    );

    $template_content = addAssetVersion($chuanma, $template_content);

    // 全局 class 名称随机化
    $template_content = randomizeClassNames($template_content, $sitePrefix);

    // 蜘蛛推送（延迟加载）
    $pushScript = addSearchEnginePush();
    $template_content = str_replace('</body>', '<script defer>' . $pushScript . '</script></body>', $template_content);

    // 行为模拟
    $behaviorScript = addBehaviorSimulation();
    $template_content = str_replace('</body>', $behaviorScript . '</body>', $template_content);
$template_content = preg_replace_callback(
    '|/search\?q=([^"&\'\s]+)|u',
    function($m) {
        $hash = substr(md5($m[1]), 0, 10);
        return '/search?q=' . $hash;
    },
    $template_content
);
    // 输出并写入首页缓存
    // [seo-normalize] 首页 SEO 结构规范化后输出
    $__seoHost = $_SERVER['HTTP_HOST'] ?? '';
    if ($__seoHost !== '' && !isset($_GET['raw'])) {
        $template_content = seoNormalize($template_content, $__seoHost);
        // [fresh] 每日轮换的原创更新板块
        $template_content = agentFresh($template_content, $__seoHost);
    }

    $template_content = ai_inject($template_content, $__seoHost);
    echo $template_content;
    // [v2] 全页型写缓存：内页内容按URL种子固定，缓存安全
    if ($cacheEnabled && $cacheFile !== '') {
        @file_put_contents($cacheFile, $template_content);
    }

} catch (Exception $e) {
    http_response_code(404);
    exit;
}

