/**
 * 火箭云控 URL 解析（与 PHP HuojianUrlHelper 对齐）
 * 长链域名动态识别，禁止写死 v3.url66.me
 */

const BUSINESS_PATH_NEEDLE = '/gds';
const LINK_QUERY_PARAM = 'link';

/**
 * @param {string} url
 */
function isHuojianLongLinkUrl(url) {
    if (!url || typeof url !== 'string') {
        return false;
    }
    try {
        const parsed = new URL(url);
        if (!parsed.pathname.includes(BUSINESS_PATH_NEEDLE)) {
            return false;
        }
        const link = (parsed.searchParams.get(LINK_QUERY_PARAM) || '').trim();
        return link !== '';
    } catch (_) {
        return false;
    }
}

/**
 * @param {string} url
 * @returns {string}
 */
function extractHuojianBusinessHost(url) {
    if (!isHuojianLongLinkUrl(url)) {
        return '';
    }
    try {
        return new URL(url).hostname.toLowerCase();
    } catch (_) {
        return '';
    }
}

/**
 * @param {string} url
 * @returns {string}
 */
function extractHuojianShareToken(url) {
    if (!url || typeof url !== 'string') {
        return '';
    }
    try {
        const parsed = new URL(url);
        if (isHuojianLongLinkUrl(url)) {
            return (parsed.searchParams.get(LINK_QUERY_PARAM) || '').trim();
        }
        const path = parsed.pathname.replace(/^\/+|\/+$/g, '');
        if (path === '' || path.includes('/')) {
            return '';
        }
        if (/^[a-zA-Z0-9]+$/.test(path)) {
            return path;
        }
    } catch (_) {
        /* ignore */
    }
    return '';
}

/**
 * @param {string} url
 */
function isHuojianShortEntryUrl(url) {
    if (isHuojianLongLinkUrl(url)) {
        return false;
    }
    return extractHuojianShareToken(url) !== '';
}

/**
 * 落地后补全 businessHostHint（多长链域名兼容）
 * @param {object} antiBot
 * @param {string} finalPageUrl
 */
function applyHuojianBusinessHostHint(antiBot, finalPageUrl) {
    if (!antiBot) {
        return antiBot;
    }
    const host = extractHuojianBusinessHost(finalPageUrl);
    if (host !== '') {
        antiBot.businessHostHint = host;
        console.log(`[Huojian] 落地业务域=${host} url=${finalPageUrl}`);
    }
    return antiBot;
}

module.exports = {
    isHuojianLongLinkUrl,
    extractHuojianBusinessHost,
    extractHuojianShareToken,
    isHuojianShortEntryUrl,
    applyHuojianBusinessHostHint,
    BUSINESS_PATH_NEEDLE,
};
