// @ts-nocheck
/**
 * 夸克网盘 — 容量查询 & 空间清理
 * 依赖 quark-api.ts 统一端点模块
 */
import * as q from './quark-api';

// ==================== 容量查询 ====================

/** 容量缓存 (3小时窗口) */
const storageCache = { bytes: 0, hourBlock: -1 };

/**
 * 快速获取容量信息 (优先 /member API，回退到 capacity/detail + 根目录统计)
 */
export async function getStorageInfoQuick(cookie, fallbackTotal?) {
    // 优先使用 /member 快速接口
    const member = await q.getMemberInfo(cookie);
    if (member && member.totalBytes > 0) {
        const currentHourBlock = Math.floor(new Date().getHours() / 3);
        storageCache.bytes = member.usedBytes;
        storageCache.hourBlock = currentHourBlock;
        return {
            total: q.formatBytes(member.totalBytes),
            totalBytes: member.totalBytes,
            used: q.formatBytes(member.usedBytes),
            usedBytes: member.usedBytes,
        };
    }

    // 回退: capacity/detail + 根目录文件大小合计
    try {
        const params = new URLSearchParams(q.getCommonParams());
        const capResp = await fetch(q.QUARK_DRIVE_HOST + q.EP.CAPACITY_DETAIL + '?' + params.toString(), {
            headers: q.getHeaders(cookie),
            signal: AbortSignal.timeout(10000),
        });
        let totalBytes = 0;
        if (capResp.ok) {
            const data = await capResp.json();
            if (data.status === 200 && data.data) {
                totalBytes = data.data.capacity_summary?.sum_capacity || 0;
                if (totalBytes === 0) {
                    const memberships = [...(data.data.effect || []), ...(data.data.expired || [])];
                    totalBytes = memberships.reduce((max, m) => Math.max(max, m.capacity || 0), 0);
                }
            }
        }
        let usedBytes = 0;
        try { const rootFiles = await q.listRootDir(cookie); for (const f of rootFiles) usedBytes += f.size || 0; } catch {}
        if (totalBytes > 0) {
            return { total: q.formatBytes(totalBytes), totalBytes, used: q.formatBytes(usedBytes), usedBytes };
        }
    } catch {}

    // 兜底：从字符串解析
    if (fallbackTotal) {
        const match = String(fallbackTotal).match(/^([\d.]+)\s*([KMGT]B?)/i);
        if (match) {
            const num = parseFloat(match[1]);
            const unit = match[2].toUpperCase();
            const multipliers = { B:1, KB:1024, MB:1048576, GB:1073741824, TB:1099511627776 };
            const m = multipliers[unit] || multipliers[unit.replace('B','')+'B'] || 0;
            if (m > 0) return { total: String(fallbackTotal), totalBytes: Math.round(num*m), used: '-', usedBytes: 0 };
        }
    }
    return { total: '-', totalBytes: 0, used: '-', usedBytes: 0 };
}

/** 获取容量信息 (兼容旧接口) */
export async function getStorageInfo(cookie, onBackgroundComplete?) {
    const result = await getStorageInfoQuick(cookie);
    if (onBackgroundComplete && result.used !== '-' && result.usedBytes > 0) {
        try { onBackgroundComplete(result.used, result.total); } catch {}
    }
    return result;
}

/** 递归遍历所有文件计算已用空间 (带 3 小时缓存) */
export async function calculateUsedSpace(cookie) {
    const currentHourBlock = Math.floor(new Date().getHours() / 3);
    if (storageCache.hourBlock === currentHourBlock && storageCache.bytes > 0) {
        return storageCache.bytes;
    }
    let totalUsed = 0;
    const stack = ['0'];
    const visited = new Set<string>();
    while (stack.length > 0) {
        const fid = stack.pop()!;
        if (visited.has(fid)) continue;
        visited.add(fid);
        const files = await q.listDirAllPages(cookie, fid);
        if (!files.length) continue;
        for (const f of files) {
            if (f.dir) stack.push(f.fid);
            else totalUsed += f.size || 0;
        }
        await new Promise(r => setTimeout(r, 50));
    }
    storageCache.bytes = totalUsed;
    storageCache.hourBlock = currentHourBlock;
    return totalUsed;
}

// ==================== 清理操作 ====================

/**
 * 永久删除文件/文件夹 (之前是移入回收站, 现改为直接永久删除)
 */
export async function trashFiles(cookie, fids) {
    return q.permanentDelete(cookie, fids);
}

/**
 * 清空回收站 (现在删除是永久删除, 此函数基本不需要了, 保留兼容)
 */
export async function emptyTrash(cookie) {
    return q.emptyTrashApi(cookie);
}

/**
 * 清理 N 天前的日期文件夹 (YYYY-MM-DD 格式)
 */
export async function cleanupOldDateFolders(cookie, days, whitelistDirs?) {
    const cutoff = new Date();
    cutoff.setDate(cutoff.getDate() - days);
    const cutoffStr = cutoff.toISOString().slice(0, 10);
    try {
        const rootItems = await q.listRootDir(cookie);
        const oldFolders = rootItems.filter(item => {
            if (!item.dir) return false;
            if (!/^\d{4}-\d{2}-\d{2}$/.test(item.file_name)) return false;
            if (whitelistDirs && whitelistDirs.includes(item.file_name)) return false;
            return item.file_name < cutoffStr;
        });
        if (oldFolders.length === 0) return { trashed: 0, errors: [] };
        const fids = oldFolders.map(f => f.fid);
        console.log('[Quark] 永久删除 ' + fids.length + ' 个旧日期文件夹 (早于 ' + cutoffStr + '): ' + oldFolders.map(f => f.file_name).join(', '));
        const ok = await trashFiles(cookie, fids);
        if (ok) return { trashed: fids.length, errors: [] };
        return { trashed: 0, errors: ['删除 API 失败: ' + fids.length + ' 个文件夹'] };
    } catch (err) {
        return { trashed: 0, errors: [err.message] };
    }
}

/**
 * 根据空间阈值清理：已用空间超过 thresholdPercent% 时删除最老的日期文件夹
 * 直到释放 deletePercent% 的总容量
 */
export async function cleanupBySpaceThreshold(cookie, thresholdPercent, deletePercent, whitelistDirs?) {
    try {
        const storage = await getStorageInfo(cookie);
        if (storage.totalBytes <= 0) return { trashed: 0, errors: [] };
        const usagePercent = (storage.usedBytes / storage.totalBytes) * 100;
        if (usagePercent < thresholdPercent) {
            console.log('[Quark] 使用率 ' + usagePercent.toFixed(1) + '% 低于阈值 ' + thresholdPercent + '%, 跳过');
            return { trashed: 0, errors: [] };
        }
        const targetBytesToFree = Math.floor(storage.totalBytes * Math.min(deletePercent, 100) / 100);
        const rootItems = await q.listRootDir(cookie);
        const dateFolders = rootItems
            .filter(item => item.dir && /^\d{4}-\d{2}-\d{2}$/.test(item.file_name))
            .filter(item => !whitelistDirs || !whitelistDirs.includes(item.file_name))
            .sort((a, b) => a.file_name.localeCompare(b.file_name));
        if (dateFolders.length === 0) return { trashed: 0, errors: [] };
        const hasSizes = dateFolders.some(f => f.size && f.size > 0);
        let cumulativeSize = 0;
        const foldersToTrash = [];
        if (hasSizes) {
            for (const folder of dateFolders) {
                foldersToTrash.push(folder);
                cumulativeSize += folder.size || 0;
                if (cumulativeSize >= targetBytesToFree) break;
            }
        } else {
            const avgSizePerFolder = storage.usedBytes / dateFolders.length;
            const estCount = Math.max(1, Math.ceil(targetBytesToFree / avgSizePerFolder));
            foldersToTrash.push(...dateFolders.slice(0, estCount));
            cumulativeSize = estCount * avgSizePerFolder;
        }
        const freedMB = (cumulativeSize / 1024 / 1024).toFixed(0);
        const targetMB = (targetBytesToFree / 1024 / 1024).toFixed(0);
        const fidsToTrash = foldersToTrash.map(f => f.fid);
        const gbTotal = (storage.totalBytes / 1024 / 1024 / 1024).toFixed(0);
        console.log('[Quark] 空间阈值清理：删除 ' + foldersToTrash.length + '/' + dateFolders.length + ' 个最老文件夹 (~' + freedMB + ' MB)，目标释放 ' + targetMB + ' MB (' + deletePercent + '% of ' + gbTotal + ' GB)');
        const ok = await trashFiles(cookie, fidsToTrash);
        if (ok) {
            console.log('[Quark] OK 空间阈值清理完成：已删除 ' + foldersToTrash.length + ' 个文件夹 (~' + freedMB + ' MB)');
            return { trashed: foldersToTrash.length, errors: [] };
        }
        return { trashed: 0, errors: ['空间阈值清理失败: ' + foldersToTrash.length + ' 个文件夹'] };
    } catch (err) {
        return { trashed: 0, errors: [err.message] };
    }
}
