// @ts-nocheck
/**
 * 夸克网盘 — 广告关键词清理模块
 * 转存完成后：删除广告文件名 + 创建警示文件夹
 * 依赖 quark-api.ts 统一端点模块
 */
import * as q from './quark-api';
import * as system_config_service from '../../admin/system-config.service';

// ==================== 配置读取 ====================

/** 从数据库读取广告关键词列表 */
export function getAdKeywords() {
    const raw = system_config_service.getSystemConfig('quark_ad_keywords') || '';
    return raw.split('\n').flatMap(line => line.split(',')).map(s => s.trim()).filter(Boolean);
}

/** 从数据库读取警示文件夹名称列表 */
export function getWarningFolderNames() {
    const raw = system_config_service.getSystemConfig('quark_warning_folder_names') || '';
    return raw.split('\n').flatMap(line => line.split(',')).map(s => s.trim()).filter(Boolean);
}

/** 从数据库读取可疑文件后缀列表 */
export function getSusExtensions() {
    const raw = system_config_service.getSystemConfig('quark_sus_extensions') || '';
    if (raw.trim()) {
        return raw.split('\n').map(s => s.trim().toLowerCase().replace(/^\./, '')).filter(Boolean);
    }
    return ['bat', 'exe', 'vbs', 'scr', 'cmd', 'com', 'pif', 'js', 'jar', 'msi', 'reg', 'inf', 'ps1'];
}

// ==================== 关键词检测 ====================

/** 检查文件名是否包含任意广告关键词 */
export function containsAdKeyword(fileName, keywords) {
    if (!keywords.length) return false;
    const lower = fileName.toLowerCase();
    return keywords.some(kw => kw && lower.includes(kw.toLowerCase()));
}

// ==================== 删除操作 ====================

/**
 * 遍历指定目录（含子目录），删除匹配广告关键词的文件和文件夹
 * 返回删除的文件数
 */
export async function deleteAdFiles(cookie, dirFid, keywords) {
    const extensions = getSusExtensions();
    if (!keywords.length && !extensions.length) return 0;
    let deletedCount = 0;
    const stack = [dirFid];
    const visited = new Set<string>();
    while (stack.length > 0) {
        const fid = stack.pop()!;
        if (visited.has(fid)) continue;
        visited.add(fid);
        await q.humanDelay();
        const files = await q.listDir(cookie, fid);
        if (!files || files.length === 0) continue;
        const toDelete: string[] = [];
        for (const file of files) {
            const ext = file.file_name.split('.').pop()?.toLowerCase() || '';
            const isSusExt = extensions.includes(ext);
            if (containsAdKeyword(file.file_name, keywords) || isSusExt) {
                toDelete.push(file.fid);
                const reason = isSusExt ? '[可疑后缀]' : '[广告关键词]';
                console.log('[Quark-AdCleanup] 标记删除: "' + file.file_name + '" (fid: ' + file.fid + ') ' + reason);
            } else if (file.dir) {
                stack.push(file.fid);
            }
        }
        if (toDelete.length > 0) {
            const deleteOk = await q.permanentDelete(cookie, toDelete);
            if (deleteOk) {
                deletedCount += toDelete.length;
                console.log('[Quark-AdCleanup] 已删除 ' + toDelete.length + ' 个广告文件');
            }
        }
    }
    return deletedCount;
}

// ==================== 警示文件夹 ====================

/**
 * 在转存根目录下创建警示文件夹
 * 文件夹名前加 emoji 和空格，让其按字母排序置顶
 */
export async function createWarningDirectories(cookie, dirNames, parentDirFid = '0') {
    if (!dirNames.length) return;
    await q.humanDelay();
    const rootFiles = await q.listDirAllPages(cookie, parentDirFid);
    const existingDirs = new Set(rootFiles.filter(f => f.dir).map(f => f.file_name));
    for (const name of dirNames) {
        let formattedName = name;
        if (!formattedName.startsWith('\u26a0\ufe0f') && !formattedName.startsWith('\u26a0')) {
            formattedName = '\u26a0\ufe0f ' + formattedName;
        }
        formattedName = formattedName.replace(/\s+/g, ' ').trim();
        if (existingDirs.has(formattedName)) {
            console.log('[Quark-AdCleanup] 警示文件夹已存在，跳过: "' + formattedName + '"');
            continue;
        }
        const result = await q.quarkCreateDir(cookie, formattedName, parentDirFid);
        if (result) {
            console.log('[Quark-AdCleanup] 已创建警示文件夹: "' + formattedName + '" (fid: ' + result.fid + ')');
        }
        existingDirs.add(formattedName);
    }
}

// ==================== 主入口 ====================

/**
 * 执行广告清理 + 创建警示文件夹
 * 在转存重命名后调用
 */
export async function runAdCleanup(cookie, savedDirFid) {
    const keywords = getAdKeywords();
    const susExtensions = getSusExtensions();
    const warningNames = getWarningFolderNames();
    let adDeleted = 0;
    let warningDirs = 0;

    if (keywords.length > 0 || susExtensions.length > 0) {
        console.log('[Quark-AdCleanup] 开始文件清理: ' + keywords.length + ' 个关键词, ' + susExtensions.length + ' 个可疑后缀');
        adDeleted = await deleteAdFiles(cookie, savedDirFid, keywords);
        console.log('[Quark-AdCleanup] 清理完成，共删除 ' + adDeleted + ' 个文件/文件夹');
    } else {
        console.log('[Quark-AdCleanup] 无关键词/可疑后缀配置，跳过清理');
    }

    if (warningNames.length > 0) {
        console.log('[Quark-AdCleanup] 开始创建警示文件夹: ' + warningNames.length + ' 个');
        await createWarningDirectories(cookie, warningNames, savedDirFid);
        warningDirs = warningNames.length;
        console.log('[Quark-AdCleanup] 警示文件夹创建完成（共 ' + warningDirs + ' 个）');
    } else {
        console.log('[Quark-AdCleanup] 无警示文件夹配置，跳过创建');
    }

    return { adDeleted, warningDirs };
}
