// 测试脚本，用于调试 getDomainInfo 函数
const fs = require('fs');
const path = require('path');

// 模拟浏览器环境的 console.log
console.log = function() {
    process.stdout.write(Array.from(arguments).join(' ') + '\n');
};

// 读取域名信息数据库
const domainInfoPath = path.join(__dirname, 'static/domain-info/domains/domain-info.json');
const domainInfoDatabase = JSON.parse(fs.readFileSync(domainInfoPath, 'utf8'));

// 模拟已加载的数据库
let domainInfoLoaded = true;

// 检查域名是否匹配
function isDomainMatch(urlValue, targetDomain, categoryId) {
    console.log('    开始匹配URL:', urlValue, '目标域名:', targetDomain, '类别ID:', categoryId);
    
    // 规范化目标域名，去除末尾的点
    const normalizedTargetDomain = targetDomain.replace(/\.$/, '').toLowerCase();
    
    try {
        // 尝试将URL值解析为完整URL
        console.log('    尝试解析URL为完整URL');
        const url = new URL(urlValue);
        let hostname = url.hostname.toLowerCase();
        // 规范化主机名，去除末尾的点
        hostname = hostname.replace(/\.$/, '');
        console.log('    解析成功，主机名:', hostname, '规范化目标域名:', normalizedTargetDomain);
        
        // 根据类别ID选择匹配方式
        if (categoryId === 2) {
            // CDN类别，使用域名后缀匹配
            if (normalizedTargetDomain.endsWith('.' + hostname) || normalizedTargetDomain === hostname) {
                console.log('    CDN域名后缀匹配成功');
                return true;
            } else {
                console.log('    CDN域名后缀不匹配');
                return false;
            }
        } else {
            // 其他类别，使用完整域名匹配
            if (hostname === normalizedTargetDomain) {
                console.log('    完整域名匹配成功');
                return true;
            } else {
                console.log('    完整域名不匹配');
                return false;
            }
        }
    } catch (e) {
        console.log('    解析URL失败，将其视为纯域名处理，错误信息:', e.message);
        // 如果是纯域名而不是完整URL
        let urlDomain = urlValue.toLowerCase();
        // 规范化纯域名，去除末尾的点
        urlDomain = urlDomain.replace(/\.$/, '');
        console.log('    处理为纯域名:', urlDomain, '规范化目标域名:', normalizedTargetDomain);
        
        // 根据类别ID选择匹配方式
        if (categoryId === 2) {
            // CDN类别，使用域名后缀匹配
            if (normalizedTargetDomain.endsWith('.' + urlDomain) || normalizedTargetDomain === urlDomain) {
                console.log('    CDN域名后缀匹配成功');
                return true;
            } else {
                console.log('    CDN域名后缀不匹配');
                return false;
            }
        } else {
            // 其他类别，使用完整域名匹配
            if (urlDomain === normalizedTargetDomain) {
                console.log('    完整域名匹配成功');
                return true;
            } else {
                console.log('    完整域名不匹配');
                return false;
            }
        }
    }
}

// 根据域名查找对应的网站信息
async function getDomainInfo(domain) {
    console.log('开始查找域名信息，域名:', domain);
    
    if (!domainInfoDatabase || !domainInfoDatabase.domains) {
        console.error('域名信息数据库无效或为空');
        return null;
    }
    
    // 规范化域名，移除可能的端口号
    const normalizedDomain = domain.replace(/:\d+$/, '').toLowerCase();
    console.log('规范化后的域名:', normalizedDomain);
    
    // 遍历所有公司
    console.log('开始遍历公司，总公司数:', Object.keys(domainInfoDatabase.domains).length);
    for (const companyKey in domainInfoDatabase.domains) {
        if (domainInfoDatabase.domains.hasOwnProperty(companyKey)) {
            console.log('检查公司:', companyKey);
            const companyData = domainInfoDatabase.domains[companyKey];
            const companyName = companyData.company || companyKey;
            
            // 遍历公司下的所有网站和类别
            for (const websiteKey in companyData) {
                if (companyData.hasOwnProperty(websiteKey) && websiteKey !== 'company') {
                    console.log('  检查网站/类别:', websiteKey);
                    const website = companyData[websiteKey];
                    
                    // 如果有URL属性，直接检查域名
                    if (website.url) {
                        // 处理字符串类型的URL
                        if (typeof website.url === 'string') {
                            console.log('    检查字符串URL:', website.url);
                            if (isDomainMatch(website.url, normalizedDomain, website.categoryId)) {
                                console.log('    匹配成功，返回网站信息');
                                return {
                                    name: website.name,
                                    icon: website.icon,
                                    categoryId: website.categoryId,
                                    categoryName: domainInfoDatabase.categories[website.categoryId] || '未知',
                                    company: website.company || companyName
                                };
                            }
                        }
                        // 处理对象类型的URL
                        else if (typeof website.url === 'object') {
                            console.log('    检查对象类型URL，包含', Object.keys(website.url).length, '个URL');
                            for (const urlKey in website.url) {
                                if (website.url.hasOwnProperty(urlKey)) {
                                    const urlValue = website.url[urlKey];
                                    console.log('      检查URL', urlKey, ':', urlValue);
                                    if (isDomainMatch(urlValue, normalizedDomain, website.categoryId)) {
                                        console.log('      匹配成功，返回网站信息');
                                        return {
                                            name: website.name,
                                            icon: website.icon,
                                            categoryId: website.categoryId,
                                            categoryName: domainInfoDatabase.categories[website.categoryId] || '未知',
                                            company: website.company || companyName
                                        };
                                    }
                                }
                            }
                        }
                    } else if (typeof website === 'object' && website !== null) {
                        // 没有URL属性，可能是嵌套的类别
                        console.log('    发现嵌套类别，进一步检查');
                        for (const nestedWebsiteKey in website) {
                            if (website.hasOwnProperty(nestedWebsiteKey) && nestedWebsiteKey !== 'company') {
                                console.log('      检查嵌套网站/类别:', nestedWebsiteKey);
                                const nestedWebsite = website[nestedWebsiteKey];
                                
                                if (nestedWebsite.url) {
                                    // 处理字符串类型的URL
                                    if (typeof nestedWebsite.url === 'string') {
                                        console.log('        检查字符串URL:', nestedWebsite.url);
                                        if (isDomainMatch(nestedWebsite.url, normalizedDomain, nestedWebsite.categoryId)) {
                                            console.log('        匹配成功，返回网站信息');
                                            return {
                                                name: nestedWebsite.name,
                                                icon: nestedWebsite.icon,
                                                categoryId: nestedWebsite.categoryId,
                                                categoryName: domainInfoDatabase.categories[nestedWebsite.categoryId] || '未知',
                                                company: nestedWebsite.company || companyName
                                            };
                                        }
                                    }
                                    // 处理对象类型的URL
                                    else if (typeof nestedWebsite.url === 'object') {
                                        console.log('        检查对象类型URL，包含', Object.keys(nestedWebsite.url).length, '个URL');
                                        for (const urlKey in nestedWebsite.url) {
                                            if (nestedWebsite.url.hasOwnProperty(urlKey)) {
                                                const urlValue = nestedWebsite.url[urlKey];
                                                console.log('          检查URL', urlKey, ':', urlValue);
                                                if (isDomainMatch(urlValue, normalizedDomain, nestedWebsite.categoryId)) {
                                                    console.log('          匹配成功，返回网站信息');
                                                    return {
                                                        name: nestedWebsite.name,
                                                        icon: nestedWebsite.icon,
                                                        categoryId: nestedWebsite.categoryId,
                                                        categoryName: domainInfoDatabase.categories[nestedWebsite.categoryId] || '未知',
                                                        company: nestedWebsite.company || companyName
                                                    };
                                                }
                                            }
                                        }
                                    }
                                } else if (typeof nestedWebsite === 'object' && nestedWebsite !== null) {
                                    // 嵌套类别中的嵌套类别，递归检查
                                    console.log('        发现二级嵌套类别，进一步检查');
                                    for (const secondNestedWebsiteKey in nestedWebsite) {
                                        if (nestedWebsite.hasOwnProperty(secondNestedWebsiteKey) && secondNestedWebsiteKey !== 'company') {
                                            console.log('          检查二级嵌套网站:', secondNestedWebsiteKey);
                                            const secondNestedWebsite = nestedWebsite[secondNestedWebsiteKey];
                                            
                                            if (secondNestedWebsite.url) {
                                                // 处理字符串类型的URL
                                                if (typeof secondNestedWebsite.url === 'string') {
                                                    console.log('            检查字符串URL:', secondNestedWebsite.url);
                                                    if (isDomainMatch(secondNestedWebsite.url, normalizedDomain, secondNestedWebsite.categoryId)) {
                                                        console.log('            匹配成功，返回网站信息');
                                                        return {
                                                            name: secondNestedWebsite.name,
                                                            icon: secondNestedWebsite.icon,
                                                            categoryId: secondNestedWebsite.categoryId,
                                                            categoryName: domainInfoDatabase.categories[secondNestedWebsite.categoryId] || '未知',
                                                            company: secondNestedWebsite.company || companyName
                                                        };
                                                    }
                                                }
                                                // 处理对象类型的URL
                                                else if (typeof secondNestedWebsite.url === 'object') {
                                                    console.log('            检查对象类型URL，包含', Object.keys(secondNestedWebsite.url).length, '个URL');
                                                    for (const urlKey in secondNestedWebsite.url) {
                                                        if (secondNestedWebsite.url.hasOwnProperty(urlKey)) {
                                                            const urlValue = secondNestedWebsite.url[urlKey];
                                                            console.log('              检查URL', urlKey, ':', urlValue);
                                                            if (isDomainMatch(urlValue, normalizedDomain, secondNestedWebsite.categoryId)) {
                                                                console.log('              匹配成功，返回网站信息');
                                                                return {
                                                                    name: secondNestedWebsite.name,
                                                                    icon: secondNestedWebsite.icon,
                                                                    categoryId: secondNestedWebsite.categoryId,
                                                                    categoryName: domainInfoDatabase.categories[secondNestedWebsite.categoryId] || '未知',
                                                                    company: secondNestedWebsite.company || companyName
                                                                };
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    console.log('        嵌套网站没有URL属性且不是对象类型');
                                }
                            }
                        }
                    } else {
                        console.log('    网站没有URL属性');
                    }
                }
            }
        }
    }
    
    console.log('未找到匹配的域名信息');
    return null;
}

// 测试 mcs.doubao.com
getDomainInfo('mcs.doubao.com').then(result => {
    console.log('\n=== 测试结果 ===');
    if (result) {
        console.log('匹配成功:', JSON.stringify(result, null, 2));
    } else {
        console.log('匹配失败');
    }
});
