跳转到内容

User:Kurgenera/MOSNUM dates mass.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
致来访者:

在您计划向本页面提交任何更改前,请知悉维基百科社群关于尊重他人专属空间的编辑指引。除非您当前正在执行符合社群广泛共识的头衔授予,或者在特定置顶区域完成必要的站务签名,否则请勿对本页面的主体内容做出任何形式的文本干扰。此外,本页面承载的全部原创文字均已基于知识共享署名-相同方式共享4.0国际协议进行公开授权,在后续任何形式的重用、分发或衍生过程中,均请严格注意并切实履行您的署名义务与授权原则。
另请注意User:MonoFinet不要搬运和使用本人的任何自动化工具,否则本人对原工具进行快速删除处理。

/*Bug:[[Special:Diff/95583324#c-Nanhuajiaren-20261114041200-请核实您的脚本!]]、[[Special:Diff/95726486]]*/
/*[[Special:Diff/95735352]]重写了脚本,采用了更加保守的正则,目前能解决以上的两个错误。*/

var _addText = "{{工具警告}}";

(function () {
    'use strict';

    // 本人不希望“不受信任的人”使用本人开发的任何用户工具,如此我宁愿封闭该工具以避免其使用。
    if (typeof mw !== 'undefined' && mw.config.get('wgUserName') === 'MonoFinet') {
        return;
    }

    if (typeof mw === 'undefined') return;

    // 统一配置项(支持外部 window.MOSNUMMassConfig 覆盖)
    const DEFAULT_CONFIG = {
        readBatchSize: 20,        // 每次批量读取页面源码的数量(1~50)
        editDelay: 1500,          // 默认写入冷却间隔(毫秒,可在面板中实时调整)
        readDelay: 150,           // 默认读取冷却间隔(毫秒,可在面板中实时调整)
        ucLimit: 500,             // 每次拉取 usercontribs 的条数
        maxQueueBuffer: 1000,     // 贡献流式队列缓冲上限(防千万级编辑内存溢出)
        maxLogDomItems: 1500,     // 页面日志 DOM 最多保留条数
        maxConsecutiveErrors: 3,  // 允许的连续异常最大次数(超过即自动暂停)
        maxJobRetries: 3,         // 单个任务最多自动尝试修复/重试次数
        maxlag: 5,                // MediaWiki 高负载退避参数
        defaultEnableZhJp: false,  // 默认勾选:中文/日文日期修复
        defaultEnableEn: true,   // 默认勾选:英文日期修复
		/*值得一提的是,目前回报的所有Bug几乎都出于中文问题。英文日期修复至今目前未发现问题*/
        defaultReviewMode: true,  // 安全选项:人工审核模式(默认勾选)
        logToConsole: true        // 是否同步输出到浏览器控制台
    };
    const CONFIG = Object.assign({}, DEFAULT_CONFIG, window.MOSNUMMassConfig || {});

    const dependencies = [
        "//en.wikipedia.org/w/index.php?title=User:Ohconfucius/script/MOSNUM_utils.js&action=raw&ctype=text/javascript"
    ];

    function injectStyles() {
        const oldStyle = document.getElementById('mosnum-mass-nuke-styles');
        if (oldStyle) oldStyle.remove();

        const style = document.createElement('style');
        style.id = 'mosnum-mass-nuke-styles';
        style.textContent = `
            #efficient-nuke-overlay {
                position: fixed !important;
                top: 0 !important; left: 0 !important; right: 0 !important; bottom: 0 !important;
                width: 100vw !important; height: 100vh !important;
                background: rgba(0, 0, 0, 0.78) !important;
                z-index: 99999 !important;
                display: flex !important;
                align-items: center !important;
                justify-content: center !important;
                margin: 0 !important; padding: 0 !important;
            }
            #efficient-nuke-modal {
                background: #fff !important;
                padding: 16px 22px !important;
                border: 1px solid #a2a9b1 !important;
                border-radius: 4px !important;
                z-index: 100000 !important;
                position: relative !important;
                top: auto !important; left: auto !important; transform: none !important;
                width: 98vw !important;
                min-width: 96vw !important;
                max-width: 99vw !important;
                height: 96vh !important;
                max-height: 98vh !important;
                box-shadow: 0 8px 30px rgba(0,0,0,0.55) !important;
                font-family: sans-serif !important;
                color: #202122 !important;
                display: flex !important;
                flex-direction: column !important;
                box-sizing: border-box !important;
            }
            @media (max-width: 768px) {
                #efficient-nuke-modal {
                    width: 94vw !important;
                    min-width: 0 !important;
                    max-width: 450px !important;
                    height: 90vh !important;
                    padding: 12px 14px !important;
                    overflow-y: auto !important;
                }
            }
            .nuke-header {
                display: flex; justify-content: space-between; align-items: center;
                border-bottom: 1px solid #c8ccd1; padding-bottom: 8px; margin-bottom: 8px; flex-shrink: 0;
            }
            .nuke-header h3 { margin: 0; font-size: 16px; color: #202122; }
            .nuke-config-banner {
                background: #f8f9fa; border: 1px solid #eaecf0; border-left: 4px solid #3366cc;
                padding: 7px 12px; font-size: 12px; color: #333; margin-bottom: 8px; flex-shrink: 0;
                display: flex; flex-wrap: wrap; gap: 10px; align-items: center; justify-content: space-between;
            }
            .nuke-config-banner code {
                background: #eaecf0; padding: 1px 5px; border-radius: 3px; font-family: monospace;
            }
            .nuke-controls-grid {
                display: grid; grid-template-columns: 1.15fr 1fr; gap: 12px; margin-bottom: 8px; flex-shrink: 0;
                width: 100%; box-sizing: border-box;
            }
            @media (max-width: 850px) {
                .nuke-controls-grid { grid-template-columns: 1fr; }
            }
            .nuke-panel {
                border: 1px solid #eaecf0; background: #fbfbfb; padding: 10px 12px; border-radius: 4px;
                box-sizing: border-box;
            }
            .nuke-tabs { display: flex; gap: 6px; margin-bottom: 8px; }
            .nuke-tab-btn {
                flex: 1; padding: 6px 10px; border: 1px solid #a2a9b1; background: #f8f9fa;
                color: #202122; cursor: pointer; border-radius: 3px; font-size: 13px; font-weight: bold;
            }
            .nuke-tab-btn.active { background: #3366cc; color: #fff; border-color: #3366cc; }
            .nuke-field { margin-bottom: 7px; font-size: 12.5px; }
            .nuke-field label { display: block; font-weight: bold; margin-bottom: 2px; }
            .nuke-field input[type="text"], .nuke-field input[type="number"], .nuke-field textarea {
                width: 100%; box-sizing: border-box; padding: 5px 8px;
                border: 1px solid #a2a9b1; border-radius: 3px; font-size: 13px;
            }
            .nuke-field textarea { min-height: 80px; max-height: 120px; resize: vertical; font-family: monospace; }
            .nuke-inline-row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
            .nuke-check-label {
                display: flex; align-items: center; gap: 6px; font-size: 13px;
                margin-bottom: 5px; cursor: pointer; user-select: none;
            }
            .nuke-safety-box {
                margin-top: 6px; padding: 7px 10px; border-radius: 4px;
                background: #fff5f5; border: 1px solid #f5b7b1; color: #b30000;
            }
            .nuke-safety-box label { color: #d33; font-weight: bold; margin-bottom: 0; }
            .nuke-deadcode-note {
                margin-top: 6px; padding: 5px 8px; background: #f0f2f5; border-radius: 3px;
                font-size: 12px; color: #54595d;
            }
            #nuke-progress-wrapper {
                height: 8px; background: #eaecf0; border-radius: 4px; margin: 4px 0; overflow: hidden; flex-shrink: 0;
            }
            #nuke-progress-bar { height: 100%; background: #3366cc; width: 0%; transition: width 0.25s; }
            #nuke-counter-bar {
                display: flex; justify-content: space-between; font-size: 12px; color: #54595d;
                margin-bottom: 8px; padding: 5px 10px; background: #f8f9fa; border: 1px solid #eaecf0;
                border-radius: 4px; flex-shrink: 0;
            }
            .nuke-counter-item { text-align: center; flex: 1; }
            .nuke-counter-val { font-weight: bold; color: #3366cc; display: block; font-size: 14px; }

            /* 人工审核 Diff 面板 */
            #nuke-review-panel {
                display: none; flex-direction: column; flex: 1.4; min-height: 220px;
                border: 2px solid #d33; border-radius: 5px; background: #fffdf8;
                margin-bottom: 8px; overflow: hidden; width: 100%; box-sizing: border-box;
            }
            .nuke-review-header {
                display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 8px;
                background: #fff5f5; border-bottom: 1px solid #f5b7b1; padding: 7px 12px; font-size: 13px;
            }
            .nuke-review-actions { display: flex; gap: 8px; }
            .nuke-review-actions button {
                padding: 5px 14px; border: none; border-radius: 3px; cursor: pointer; font-weight: bold; font-size: 13px;
            }
            #nuke-review-approve { background: #00af89; color: #fff; }
            #nuke-review-skip { background: #72777d; color: #fff; }
            #nuke-review-diff-body {
                flex: 1; overflow: auto; padding: 8px 12px; background: #fff; font-size: 12.5px;
            }
            #nuke-review-diff-body table.diff { width: 100%; border-collapse: collapse; table-layout: fixed; }
            #nuke-review-diff-body td { word-break: break-all; padding: 2px 5px; vertical-align: top; }
            #nuke-review-diff-body .diff-addedline { background: #e6ffec; }
            #nuke-review-diff-body .diff-deletedline { background: #ffebe9; }
            #nuke-review-diff-body .diff-context { background: #f8f9fa; color: #54595d; }
            #nuke-review-diff-body ins.diffchange { background: #abf2bc; text-decoration: none; font-weight: bold; }
            #nuke-review-diff-body del.diffchange { background: #ff818266; text-decoration: none; font-weight: bold; }
            .nuke-fallback-diff { font-family: monospace; white-space: pre-wrap; margin: 0; }
            .nuke-fallback-del { background: #ffebe9; color: #82071e; display: block; padding: 2px 6px; }
            .nuke-fallback-add { background: #e6ffec; color: #116329; display: block; padding: 2px 6px; }

            .nuke-log-toolbar {
                display: flex; justify-content: space-between; align-items: center;
                margin-bottom: 4px; font-size: 12px; flex-shrink: 0;
            }
            #efficient-nuke-log {
                flex: 1; min-height: 150px; margin: 0; border: 1px solid #c8ccd1; width: 100%; box-sizing: border-box;
                padding: 8px 12px; overflow-y: auto; font-size: 12px; line-height: 1.45;
                list-style: none; background: #1e1e1e; color: #e0e0e0; border-radius: 4px;
                font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
            }
            #efficient-nuke-log li {
                margin-bottom: 4px; border-bottom: 1px solid #2d2d2d; padding-bottom: 4px;
                word-break: break-all; white-space: pre-wrap;
            }
            #efficient-nuke-log li.log-success { color: #7ee787; }
            #efficient-nuke-log li.log-skip { color: #8b949e; }
            #efficient-nuke-log li.log-warn { color: #f2cc60; }
            #efficient-nuke-log li.log-fail { color: #ff7b72; }
            #efficient-nuke-log li.log-info { color: #d2a8ff; }
            #efficient-nuke-log.hide-skip li.log-skip { display: none; }
            .nuke-buttons { display: flex; gap: 10px; margin-top: 8px; flex-shrink: 0; }
            .nuke-buttons button {
                flex: 1; padding: 9px 14px; background-color: #3366cc; color: white;
                border: none; border-radius: 4px; cursor: pointer; font-size: 14px; font-weight: bold;
            }
            .nuke-buttons button:disabled { opacity: 0.5; cursor: not-allowed; }
            .nuke-mini-btn {
                padding: 3px 8px; font-size: 12px; border: 1px solid #a2a9b1;
                background: #fff; color: #202122; border-radius: 3px; cursor: pointer;
            }
            #nuke-launch-link { font-weight: bold; color: #d33; cursor: pointer; }
        `;
        document.head.appendChild(style);
    }

    // JS 行内强制锁定桌面端/手机端宽度,防止任何外部或缓存 CSS 抢占
    function applyResponsiveModalSize() {
        const modal = document.getElementById('efficient-nuke-modal');
        if (!modal) return;

        if (window.innerWidth <= 768) {
            modal.style.setProperty('width', '94vw', 'important');
            modal.style.setProperty('min-width', '0', 'important');
            modal.style.setProperty('max-width', '450px', 'important');
            modal.style.setProperty('height', '90vh', 'important');
            modal.style.setProperty('overflow-y', 'auto', 'important');
        } else {
            modal.style.setProperty('width', '98vw', 'important');
            modal.style.setProperty('min-width', '96vw', 'important');
            modal.style.setProperty('max-width', '99vw', 'important');
            modal.style.setProperty('height', '96vh', 'important');
            modal.style.setProperty('overflow-y', 'visible', 'important');
        }
    }

    let state = null;
    let enDependencyLoaded = false;

    function resetState() {
        state = {
            mode: 'contrib',
            enableZhJp: CONFIG.defaultEnableZhJp,
            enableEn: CONFIG.defaultEnableEn,
            reviewMode: CONFIG.defaultReviewMode,
            editDelay: CONFIG.editDelay,
            readDelay: CONFIG.readDelay,
            isRunning: false,
            isPaused: false,
            isAborted: false,
            seenTitles: new Set(),
            pendingQueue: [],
            reviewQueue: [],
            currentReviewJob: null,
            editQueue: [],
            totalDiscovered: 0,
            totalProcessed: 0,
            successCount: 0,
            skipCount: 0,
            failCount: 0,
            consecutiveErrors: 0,
            targetUser: '',
            namespace: '0',
            topOnly: false,
            maxPages: 0,
            uccontinue: '',
            contribDone: false,
            isFetchingContrib: false,
            isFetchingContent: false,
            isEditing: false,
            rawLogHistory: []
        };
    }
    resetState();

    // =========================================================================
    // 健壮的 Wikitext 解析器(仅修正 {{Cite...}} / {{Citation}} + 无条件死代码清理)
    // =========================================================================

    function isCitationTemplateName(rawName) {
        const name = rawName.replace(/[\s_]+/g, ' ').trim().toLowerCase();
        if (name === 'citation' || name === 'cite') return true;
        if (/^cite[\s-]/.test(name)) {
            const excluded = new Set(['cite check', 'cite needed', 'cite-needed', 'cite this page']);
            return !excluded.has(name);
        }
        return false;
    }

    function isUseDmyMdyTemplateName(rawName) {
        const name = rawName.replace(/[\s_]+/g, ' ').trim().toLowerCase();
        return /^use (?:dmy|mdy) dates$/.test(name);
    }

    function isValidYMD(y, m, d) {
        const year = parseInt(y, 10);
        const month = parseInt(m, 10);
        const day = parseInt(d, 10);
        if (year < 1000 || year > 2999 || month < 1 || month > 12 || day < 1 || day > 31) {
            return false;
        }
        const dt = new Date(Date.UTC(year, month - 1, day));
        return dt.getUTCFullYear() === year &&
            dt.getUTCMonth() === month - 1 &&
            dt.getUTCDate() === day;
    }

    function scanWikitextTargets(text) {
        const len = text.length;
        let i = 0;
        const stack = [];
        let linkDepth = 0;
        let tripleBraceDepth = 0;
        const paramRanges = [];
        const deadTemplateRanges = [];

        const startParamIfCite = (pos) => {
            if (stack.length > 0 && linkDepth === 0) {
                const top = stack[stack.length - 1];
                if (top.isCite) {
                    if (top.currentParamStart !== -1) {
                        paramRanges.push({ start: top.currentParamStart, end: pos });
                    }
                    top.currentParamStart = pos;
                }
            }
        };

        const closeParamIfCite = (pos) => {
            if (stack.length > 0) {
                const top = stack[stack.length - 1];
                if (top.isCite && top.currentParamStart !== -1) {
                    paramRanges.push({ start: top.currentParamStart, end: pos });
                    top.currentParamStart = -1;
                }
            }
        };

        while (i < len) {
            if (text.startsWith('<!--', i)) {
                const endComment = text.indexOf('-->', i + 4);
                i = endComment === -1 ? len : endComment + 3;
                continue;
            }

            if (text[i] === '<') {
                const tagMatch = text.slice(i).match(/^<(nowiki|pre|syntaxhighlight|source|math)(?:\s[^>]*)?>/i);
                if (tagMatch) {
                    const closeRegex = new RegExp(`</${tagMatch[1]}\\s*>`, 'i');
                    const afterOpen = i + tagMatch[0].length;
                    const closeMatch = text.slice(afterOpen).match(closeRegex);
                    i = closeMatch ? afterOpen + closeMatch.index + closeMatch[0].length : len;
                    continue;
                }
            }

            if (text.startsWith('{{{', i)) {
                tripleBraceDepth++;
                i += 3;
                continue;
            }
            if (tripleBraceDepth > 0 && text.startsWith('}}}', i)) {
                tripleBraceDepth--;
                i += 3;
                continue;
            }

            if (text.startsWith('{{', i)) {
                let nameEnd = i + 2;
                while (nameEnd < len) {
                    if (text[nameEnd] === '|' || text.startsWith('}}', nameEnd) || text.startsWith('<!--', nameEnd) || text.startsWith('{{', nameEnd)) {
                        break;
                    }
                    nameEnd++;
                }
                const rawName = text.slice(i + 2, nameEnd);
                stack.push({
                    start: i,
                    isCite: isCitationTemplateName(rawName),
                    isUseDates: isUseDmyMdyTemplateName(rawName),
                    currentParamStart: -1
                });
                i += 2;
                continue;
            }

            if (text.startsWith('}}', i)) {
                if (stack.length > 0) {
                    closeParamIfCite(i);
                    const top = stack.pop();
                    if (top.isUseDates) {
                        let end = i + 2;
                        const lineBeforeStart = text.lastIndexOf('\n', top.start - 1);
                        const prefixOnLine = text.slice(lineBeforeStart + 1, top.start);
                        if (/^[ \t]*$/.test(prefixOnLine)) {
                            const nlMatch = text.slice(end).match(/^[ \t]*\r?\n/);
                            if (nlMatch) {
                                end += nlMatch[0].length;
                            }
                        }
                        deadTemplateRanges.push({ start: top.start, end });
                    }
                    i += 2;
                    continue;
                }
            }

            if (text.startsWith('[[', i)) {
                linkDepth++;
                i += 2;
                continue;
            }
            if (text.startsWith(']]', i)) {
                if (linkDepth > 0) linkDepth--;
                i += 2;
                continue;
            }

            if (text[i] === '|') {
                startParamIfCite(i);
                i += 1;
                continue;
            }

            i++;
        }

        return { paramRanges, deadTemplateRanges };
    }

    const DATE_PARAM_KEY_RE = /^(?:(?:access|archive|publication|orig|air|lay|pmc-embargo|doi-broken)-?)?date$/i;

    function runStableFixes(originalText, options) {
        const { paramRanges, deadTemplateRanges } = scanWikitextTargets(originalText);
        const edits = [];
        const changeDetails = [];

        // A. 死代码规则 1:无论如何都移除页面级 {{use dmy/mdy dates}}
        for (const dt of deadTemplateRanges) {
            edits.push({ start: dt.start, end: dt.end, replacement: '' });
            changeDetails.push(`${originalText.slice(dt.start, dt.end).trim()} -> [死代码移除]`);
        }

        // B. 仅针对 {{Cite...}} / {{Citation}} 内部参数
        for (const range of paramRanges) {
            const rawParam = originalText.slice(range.start, range.end);

            // 死代码规则 2:无论如何都移除 |和書 / |洋書(含 |1=和書 / |1=洋書)
            if (/^\|\s*(?:1\s*=\s*)?(?:和書|洋書)\s*$/i.test(rawParam)) {
                edits.push({ start: range.start, end: range.end, replacement: '' });
                changeDetails.push(`${rawParam.trim()} -> [死代码移除]`);
                continue;
            }

            const kvMatch = rawParam.match(/^(\|\s*)([^=\s][^=]*?)(\s*=\s*)([\s\S]*)$/);
            if (!kvMatch) continue;

            const prefix = kvMatch[1];
            const keyRaw = kvMatch[2];
            const eqPart = kvMatch[3];
            const valRaw = kvMatch[4];
            const keyClean = keyRaw.trim().toLowerCase();

            // 死代码规则 3:无论如何都移除 |df=...
            if (keyClean === 'df') {
                const dfValMatch = valRaw.match(/^([\s\S]*?)(\s*(?:<!--[\s\S]*?-->\s*)*)$/);
                const dfCore = dfValMatch ? dfValMatch[1].trim() : valRaw.trim();
                if (/^[\w-]*$/.test(dfCore)) {
                    edits.push({ start: range.start, end: range.end, replacement: '' });
                    changeDetails.push(`${rawParam.trim()} -> [死代码移除df]`);
                    continue;
                }
            }

            // C. 可选的日期格式转换(仅限日期类参数)
            if (!DATE_PARAM_KEY_RE.test(keyClean)) continue;

            const valMatch = valRaw.match(/^([\s\S]*?)(\s*(?:<!--[\s\S]*?-->\s*)*)$/);
            const coreVal = valMatch[1].trim();
            const trailing = valMatch[2];
            if (!coreVal) continue;

            let newCoreVal = coreVal;

            if (options.enableZhJp) {
                const zhMatch = newCoreVal.match(/^(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日$/);
                if (zhMatch && isValidYMD(zhMatch[1], zhMatch[2], zhMatch[3])) {
                    newCoreVal = `${zhMatch[1]}-${zhMatch[2].padStart(2, '0')}-${zhMatch[3].padStart(2, '0')}`;
                }
            }

            if (options.enableEn && newCoreVal === coreVal && typeof ohc !== 'undefined' && ohc.dateutil) {
                let wrapped = `|date=${newCoreVal}|`;
                wrapped = ohc.dateutil.regex(wrapped, /(\|\s*date\s*)=\s*@Day @Month,? @YYYY(?=[\s]*[|}])/gi, "$1=@YYYY-@MM-@DD");
                wrapped = ohc.dateutil.regex(wrapped, /(\|\s*date\s*)=\s*@Month @Day,? @YYYY(?=[\s]*[|}])/gi, "$1=@YYYY-@MM-@DD");
                if (wrapped.startsWith('|date=') && wrapped.endsWith('|')) {
                    const candidate = wrapped.slice(6, -1).trim();
                    if (candidate && candidate !== newCoreVal) {
                        newCoreVal = candidate;
                    }
                }
            }

            if (newCoreVal !== coreVal) {
                const replacement = `${prefix}${keyRaw}${eqPart}${newCoreVal}${trailing}`;
                edits.push({ start: range.start, end: range.end, replacement });
                changeDetails.push(`|${keyRaw.trim()}=${coreVal} -> ${newCoreVal}`);
            }
        }

        edits.sort((a, b) => a.start - b.start);
        let resultText = '';
        let cursor = 0;
        for (const edit of edits) {
            if (edit.start < cursor) continue;
            resultText += originalText.slice(cursor, edit.start) + edit.replacement;
            cursor = edit.end;
        }
        resultText += originalText.slice(cursor);

        return {
            hasChanges: resultText !== originalText,
            text: resultText,
            changes: changeDetails
        };
    }

    // =========================================================================
    // UI、日志与异常处理辅助
    // =========================================================================

    function appendLog(text, type = 'info') {
        const timestamp = new Date().toLocaleTimeString('zh-CN', { hour12: false });
        const lineText = `[${timestamp}] ${text}`;
        if (state) state.rawLogHistory.push(lineText);
        if (CONFIG.logToConsole && (type === 'success' || type === 'warn' || type === 'fail')) {
            console.log(`[MOSNUM-Mass] ${lineText}`);
        }

        const logList = document.getElementById('efficient-nuke-log');
        if (!logList) return;

        const li = document.createElement('li');
        li.className = `log-${type}`;
        li.textContent = lineText;
        logList.appendChild(li);

        while (logList.children.length > CONFIG.maxLogDomItems) {
            logList.removeChild(logList.firstChild);
        }
        logList.scrollTop = logList.scrollHeight;
    }

    function updateConfigBanner() {
        const banner = document.getElementById('nuke-config-banner');
        if (!banner || !state) return;

        const rules = ['死代码固定清理(|和書/|洋書/|df=/use dmy&mdy)'];
        if (state.enableZhJp) rules.push('中文/日文日期');
        if (state.enableEn) rules.push('英文日期');

        banner.innerHTML = `
            <div>
                <strong>Config 实时状态:</strong>
                模式=<code>${state.mode === 'contrib' ? '用户贡献流式' : '列表批量'}</code> |
                规则=<code>${rules.join(' + ')}</code> |
                审核=<code style="color:${state.reviewMode ? '#00af89' : '#d33'};">${state.reviewMode ? '人工Diff审核后保存' : '自动写入(无审核)'}</code> |
                冷却=<code>读${state.readDelay}ms / 写${state.editDelay}ms</code> |
                连续异常=<code style="color:${state.consecutiveErrors > 0 ? '#d33' : '#333'};">${state.consecutiveErrors}/${CONFIG.maxConsecutiveErrors}</code>
            </div>
            <div>
                断点游标:<code>${state.uccontinue || '无'}</code>
            </div>
        `;
    }

    function updateCounters() {
        if (!document.getElementById('efficient-nuke-overlay')) return;
        document.getElementById('val-total').textContent = state.totalDiscovered;
        document.getElementById('val-queue').textContent =
            state.pendingQueue.length + state.reviewQueue.length + (state.currentReviewJob ? 1 : 0) + state.editQueue.length;
        document.getElementById('val-success').textContent = state.successCount;
        document.getElementById('val-skip').textContent = state.skipCount;
        document.getElementById('val-fail').textContent = state.failCount;

        const denom = state.totalDiscovered > 0 ? state.totalDiscovered : 1;
        const pct = Math.min(100, (state.totalProcessed / denom) * 100);
        document.getElementById('nuke-progress-bar').style.width = pct.toFixed(1) + '%';
        updateConfigBanner();
    }

    function triggerAutoPause(reason) {
        state.isPaused = true;
        const btn = document.getElementById('nuke-pause-btn');
        if (btn) {
            btn.textContent = '继续(已因异常自动暂停)';
            btn.style.backgroundColor = '#00af89';
        }
        appendLog(`[自动暂停] ${reason}!已安全保留当前队列与断点游标,请排查后点击“继续”。`, 'fail');
        updateCounters();
    }

    function checkAllFinished() {
        if (!state.isRunning || state.isAborted) return;
        const fetchDone = state.mode === 'list' || state.contribDone;
        if (fetchDone &&
            !state.isFetchingContrib &&
            !state.isFetchingContent &&
            !state.isEditing &&
            !state.currentReviewJob &&
            state.pendingQueue.length === 0 &&
            state.reviewQueue.length === 0 &&
            state.editQueue.length === 0) {
            state.isRunning = false;
            appendLog('====================================', 'info');
            appendLog(`全部任务执行完毕!共处理 ${state.totalProcessed} 个页面,成功修改 ${state.successCount},跳过 ${state.skipCount},失败 ${state.failCount}。`, 'info');
            const startBtn = document.getElementById('nuke-start-btn');
            const pauseBtn = document.getElementById('nuke-pause-btn');
            if (startBtn) {
                startBtn.disabled = false;
                startBtn.style.display = 'block';
                startBtn.textContent = '重新开始';
            }
            if (pauseBtn) pauseBtn.style.display = 'none';
        }
    }

    // =========================================================================
    // 人工 Diff 审核逻辑(原生 action=compare + 本地兜底)
    // =========================================================================

    function buildFallbackDiffHtml(oldText, newText) {
        const oldLines = oldText.split('\n');
        const newLines = newText.split('\n');
        const maxLen = Math.max(oldLines.length, newLines.length);
        let html = '<pre class="nuke-fallback-diff">';
        for (let i = 0; i < maxLen; i++) {
            const a = oldLines[i];
            const b = newLines[i];
            if (a !== b) {
                html += `<span style="color:#54595d;">@@ 第 ${i + 1} 行 @@</span>\n`;
                if (a !== undefined) html += `<span class="nuke-fallback-del">- ${mw.html.escape(a)}</span>`;
                if (b !== undefined) html += `<span class="nuke-fallback-add">+ ${mw.html.escape(b)}</span>`;
            }
        }
        html += '</pre>';
        return html;
    }

    function openReviewPane(job) {
        state.currentReviewJob = job;
        updateCounters();

        const panel = document.getElementById('nuke-review-panel');
        const titleEl = document.getElementById('nuke-review-title');
        const diffBody = document.getElementById('nuke-review-diff-body');
        if (!panel || !titleEl || !diffBody) return;

        panel.style.display = 'flex';
        const pageUrl = mw.util.getUrl(job.title);
        titleEl.innerHTML = `待审核页面:<a href="${mw.html.escape(pageUrl)}" target="_blank" rel="noopener">${mw.html.escape(job.title)}</a> (${job.changes.length} 处改动,队列余 ${state.reviewQueue.length} 篇)`;
        diffBody.innerHTML = '<div style="color:#54595d;padding:10px;">正在向 MediaWiki 请求原生 Diff 对比视图...</div>';

        const api = new mw.Api();
        api.post({
            action: 'compare',
            fromslots: 'main',
            'fromtext-main': job.originalText,
            toslots: 'main',
            'totext-main': job.text,
            prop: 'diff',
            formatversion: 2,
            format: 'json'
        }).done((data) => {
            if (!state.currentReviewJob || state.currentReviewJob.title !== job.title) return;
            const body = data && data.compare && data.compare.body;
            if (body) {
                diffBody.innerHTML = `
                    <div style="margin-bottom:6px;font-size:12px;color:#54595d;">
                        改动摘要:${mw.html.escape(job.changes.join(' | '))}
                    </div>
                    <table class="diff">
                        <colgroup>
                            <col class="diff-marker"><col class="diff-content">
                            <col class="diff-marker"><col class="diff-content">
                        </colgroup>
                        <tbody>${body}</tbody>
                    </table>
                `;
            } else {
                diffBody.innerHTML = buildFallbackDiffHtml(job.originalText, job.text);
            }
        }).fail(() => {
            if (!state.currentReviewJob || state.currentReviewJob.title !== job.title) return;
            diffBody.innerHTML = '<div style="color:#b30000;margin-bottom:4px;">原生 Diff 请求失败,已切换本地对比:</div>' +
                buildFallbackDiffHtml(job.originalText, job.text);
        });
    }

    function closeReviewPane() {
        const panel = document.getElementById('nuke-review-panel');
        if (panel) panel.style.display = 'none';
    }

    // =========================================================================
    // 生产者-消费者流水线(含自动异常修复与 >3 次自动暂停)
    // =========================================================================

    function schedulePipeline() {
        if (!state.isRunning || state.isPaused || state.isAborted) return;

        if (state.mode === 'contrib' &&
            !state.contribDone &&
            !state.isFetchingContrib &&
            state.pendingQueue.length < CONFIG.maxQueueBuffer) {
            fetchNextContribBatch();
        }

        const reviewNotFull = !state.reviewMode || state.reviewQueue.length < 10;
        if (!state.isFetchingContent &&
            state.pendingQueue.length > 0 &&
            reviewNotFull &&
            state.editQueue.length < CONFIG.readBatchSize * 2) {
            fetchNextContentBatch();
        }

        if (state.reviewMode && !state.currentReviewJob && state.reviewQueue.length > 0) {
            const nextReview = state.reviewQueue.shift();
            openReviewPane(nextReview);
        }

        if (!state.isEditing && state.editQueue.length > 0) {
            processNextEdit();
        }

        checkAllFinished();
    }

    function fetchNextContribBatch() {
        if (state.isAborted || state.isPaused || state.contribDone) return;
        state.isFetchingContrib = true;

        const api = new mw.Api();
        const params = {
            action: 'query',
            list: 'usercontribs',
            ucuser: state.targetUser,
            uclimit: String(CONFIG.ucLimit),
            ucnamespace: state.namespace || '0',
            maxlag: CONFIG.maxlag,
            format: 'json'
        };
        if (state.topOnly) params.ucshow = 'top';
        if (state.uccontinue) params.uccontinue = state.uccontinue;

        api.get(params).done((data) => {
            state.isFetchingContrib = false;
            if (state.isAborted) return;

            state.consecutiveErrors = 0;
            const edits = (data.query && data.query.usercontribs) ? data.query.usercontribs : [];
            let addedInBatch = 0;

            for (const edit of edits) {
                if (state.maxPages > 0 && state.totalDiscovered >= state.maxPages) {
                    state.contribDone = true;
                    break;
                }
                if (!state.seenTitles.has(edit.title)) {
                    state.seenTitles.add(edit.title);
                    state.pendingQueue.push(edit.title);
                    state.totalDiscovered++;
                    addedInBatch++;
                }
            }

            if (data.continue && data.continue.uccontinue && !state.contribDone) {
                state.uccontinue = data.continue.uccontinue;
                const cursorInput = document.getElementById('nuke-uccontinue');
                if (cursorInput) cursorInput.value = state.uccontinue;
            } else {
                state.contribDone = true;
                appendLog(`用户贡献提取完成,累计发现 ${state.totalDiscovered} 个不重复页面。`, 'info');
            }

            if (addedInBatch > 0) {
                appendLog(`提取一批贡献:新增 ${addedInBatch} 个待扫页面(累计 ${state.totalDiscovered})。`, 'info');
            }

            updateCounters();
            schedulePipeline();
        }).fail((code) => {
            state.isFetchingContrib = false;
            state.consecutiveErrors++;
            updateCounters();

            if (state.consecutiveErrors > CONFIG.maxConsecutiveErrors) {
                triggerAutoPause(`提取用户贡献连续异常超过 ${CONFIG.maxConsecutiveErrors} 次 [${code}]`);
                return;
            }
            const backoff = Math.min(10000, 1500 * state.consecutiveErrors);
            appendLog(`[异常修复 ${state.consecutiveErrors}/${CONFIG.maxConsecutiveErrors}] 提取用户贡献失败 (${code}),${backoff}ms 后自动重试...`, 'warn');
            setTimeout(schedulePipeline, backoff);
        });
    }

    function fetchNextContentBatch() {
        if (state.isAborted || state.isPaused || state.pendingQueue.length === 0) return;
        state.isFetchingContent = true;

        const batchTitles = state.pendingQueue.splice(0, CONFIG.readBatchSize);
        const api = new mw.Api();

        api.post({
            action: 'query',
            prop: 'revisions',
            titles: batchTitles.join('|'),
            rvprop: 'content|timestamp',
            rvslots: 'main',
            maxlag: CONFIG.maxlag,
            format: 'json'
        }).done((data) => {
            state.isFetchingContent = false;
            if (state.isAborted) return;

            state.consecutiveErrors = 0;
            const pages = (data.query && data.query.pages) ? data.query.pages : {};
            let hasWork = false;

            for (const pageId of Object.keys(pages)) {
                const page = pages[pageId];
                const title = page.title;

                if (page.missing !== undefined || parseInt(pageId, 10) < 0) {
                    appendLog(`[不存在] 跳过已删除页面: ${title}`, 'fail');
                    state.failCount++;
                    state.totalProcessed++;
                    continue;
                }
                if (!page.revisions || !page.revisions[0]) {
                    appendLog(`[无版本] 跳过异常页面: ${title}`, 'fail');
                    state.failCount++;
                    state.totalProcessed++;
                    continue;
                }

                const rev = page.revisions[0];
                const originalText = (rev.slots && rev.slots.main) ? rev.slots.main['*'] : rev['*'];
                const basetimestamp = rev.timestamp;

                const result = runStableFixes(originalText, {
                    enableZhJp: state.enableZhJp,
                    enableEn: state.enableEn
                });

                if (!result.hasChanges) {
                    appendLog(`[无改动] ${title}`, 'skip');
                    state.skipCount++;
                    state.totalProcessed++;
                } else if (state.reviewMode) {
                    state.reviewQueue.push({
                        title,
                        originalText,
                        text: result.text,
                        basetimestamp,
                        changes: result.changes,
                        retries: 0
                    });
                    hasWork = true;
                } else {
                    state.editQueue.push({
                        title,
                        text: result.text,
                        basetimestamp,
                        changes: result.changes,
                        retries: 0
                    });
                    hasWork = true;
                }
            }

            updateCounters();
            setTimeout(schedulePipeline, hasWork ? 50 : state.readDelay);
        }).fail((code) => {
            state.isFetchingContent = false;
            state.pendingQueue.unshift(...batchTitles);
            state.consecutiveErrors++;
            updateCounters();

            if (state.consecutiveErrors > CONFIG.maxConsecutiveErrors) {
                triggerAutoPause(`批量读取页面源码连续异常超过 ${CONFIG.maxConsecutiveErrors} 次 [${code}]`);
                return;
            }
            const backoff = Math.min(10000, Math.max(state.readDelay, 1500 * state.consecutiveErrors));
            appendLog(`[异常修复 ${state.consecutiveErrors}/${CONFIG.maxConsecutiveErrors}] 批量读取失败 (${code}),${backoff}ms 后重试...`, 'warn');
            setTimeout(schedulePipeline, backoff);
        });
    }

    function buildEditSummary() {
        const modes = [];
        if (state.enableZhJp) modes.push('中日文日期');
        if (state.enableEn) modes.push('英文日期');
        const datePart = modes.length ? `修正参考资料中的${modes.join('与')}格式并` : '';
        return `基于[[维基百科:格式手册/日期和数字|格式手册]]${datePart}清理无效引用参数,由[[User:Kurgenera/MOSNUM dates mass.js]]驱动`;
    }

    function recoverEditConflict(job) {
        appendLog(`[自动修复尝试 ${job.retries}/${CONFIG.maxJobRetries}] ${job.title} 发生编辑冲突,正在重抓最新源码重算...`, 'warn');
        const api = new mw.Api();
        api.get({
            action: 'query',
            prop: 'revisions',
            titles: job.title,
            rvprop: 'content|timestamp',
            rvslots: 'main',
            maxlag: CONFIG.maxlag,
            format: 'json'
        }).done((data) => {
            state.isEditing = false;
            if (state.isAborted) return;

            const pages = data.query && data.query.pages ? data.query.pages : {};
            const pageId = Object.keys(pages)[0];
            const page = pages[pageId];
            if (!page || page.missing !== undefined || !page.revisions || !page.revisions[0]) {
                appendLog(`[修复失败] ${job.title} 重抓时页面异常或已删除。`, 'fail');
                state.failCount++;
                state.totalProcessed++;
                updateCounters();
                setTimeout(schedulePipeline, state.editDelay);
                return;
            }

            const rev = page.revisions[0];
            const latestText = (rev.slots && rev.slots.main) ? rev.slots.main['*'] : rev['*'];
            const result = runStableFixes(latestText, {
                enableZhJp: state.enableZhJp,
                enableEn: state.enableEn
            });

            if (!result.hasChanges) {
                appendLog(`[冲突已自愈] ${job.title} 最新版本已无需改动,跳过。`, 'skip');
                state.consecutiveErrors = 0;
                state.skipCount++;
                state.totalProcessed++;
                updateCounters();
                setTimeout(schedulePipeline, state.readDelay);
            } else {
                job.text = result.text;
                job.basetimestamp = rev.timestamp;
                job.changes = result.changes;
                state.editQueue.unshift(job);
                updateCounters();
                setTimeout(schedulePipeline, state.editDelay);
            }
        }).fail((code) => {
            state.isEditing = false;
            state.consecutiveErrors++;
            if (state.consecutiveErrors > CONFIG.maxConsecutiveErrors) {
                state.editQueue.unshift(job);
                triggerAutoPause(`冲突重抓连续异常超过 ${CONFIG.maxConsecutiveErrors} 次 [${code}]`);
                return;
            }
            state.editQueue.unshift(job);
            setTimeout(schedulePipeline, 2000);
        });
    }

    function processNextEdit() {
        if (state.isAborted || state.isPaused || state.editQueue.length === 0) return;
        state.isEditing = true;

        const job = state.editQueue.shift();
        const api = new mw.Api();

        api.postWithToken('csrf', {
            action: 'edit',
            title: job.title,
            text: job.text,
            summary: buildEditSummary(),
            minor: true,
            basetimestamp: job.basetimestamp,
            maxlag: CONFIG.maxlag,
            bot: false
        }).done((editData) => {
            state.isEditing = false;
            if (editData.edit && editData.edit.result === 'Success') {
                state.consecutiveErrors = 0;
                state.totalProcessed++;
                appendLog(`[已修正] ${job.title} (${job.changes.length}处):\n  - ${job.changes.join('\n  - ')}`, 'success');
                state.successCount++;
                updateCounters();
                setTimeout(schedulePipeline, state.editDelay);
            } else {
                state.consecutiveErrors++;
                job.retries = (job.retries || 0) + 1;
                if (state.consecutiveErrors > CONFIG.maxConsecutiveErrors) {
                    state.editQueue.unshift(job);
                    triggerAutoPause(`写入返回异常连续超过 ${CONFIG.maxConsecutiveErrors} 次`);
                    return;
                }
                if (job.retries <= CONFIG.maxJobRetries) {
                    appendLog(`[异常修复 ${job.retries}/${CONFIG.maxJobRetries}] ${job.title} 返回未保存,放回队列重试...`, 'warn');
                    state.editQueue.unshift(job);
                } else {
                    state.totalProcessed++;
                    state.failCount++;
                    appendLog(`[失败] ${job.title} 重试耗尽仍未保存。`, 'fail');
                }
                updateCounters();
                setTimeout(schedulePipeline, Math.max(state.editDelay, 2000));
            }
        }).fail((code, errData) => {
            const info = (errData && errData.error && errData.error.info) ? ` (${errData.error.info})` : '';
            state.consecutiveErrors++;
            job.retries = (job.retries || 0) + 1;

            if (state.consecutiveErrors > CONFIG.maxConsecutiveErrors) {
                state.isEditing = false;
                if (job.retries <= CONFIG.maxJobRetries) state.editQueue.unshift(job);
                triggerAutoPause(`写入 ${job.title} 连续异常超过 ${CONFIG.maxConsecutiveErrors} 次 [${code}]${info}`);
                return;
            }

            if (code === 'editconflict' && job.retries <= CONFIG.maxJobRetries) {
                recoverEditConflict(job);
                return;
            }

            state.isEditing = false;
            const unrecoverable = new Set(['protectedpage', 'cantcreate', 'spamdetected', 'abusefilter-disallowed', 'blocked']);
            if (!unrecoverable.has(code) && job.retries <= CONFIG.maxJobRetries) {
                const backoff = Math.max(state.editDelay, 2000 * job.retries);
                appendLog(`[异常修复 ${job.retries}/${CONFIG.maxJobRetries}] 写入 ${job.title} 出错 [${code}]${info},${backoff}ms 后自动重试...`, 'warn');
                state.editQueue.unshift(job);
                updateCounters();
                setTimeout(schedulePipeline, backoff);
            } else {
                state.totalProcessed++;
                state.failCount++;
                appendLog(`[失败] 写入 ${job.title} 终止 [${code}]${info}`, 'fail');
                updateCounters();
                setTimeout(schedulePipeline, state.editDelay);
            }
        });
    }

    // =========================================================================
    // 模态框与交互绑定
    // =========================================================================

    function parseListInput(raw) {
        const lines = raw.split(/\r?\n/);
        const titles = [];
        const seen = new Set();
        for (let line of lines) {
            line = line.trim();
            if (!line) continue;
            if (line.startsWith('[[') && line.endsWith(']]')) line = line.slice(2, -2);
            const pipeIdx = line.indexOf('|');
            if (pipeIdx !== -1) line = line.slice(0, pipeIdx);
            const hashIdx = line.indexOf('#');
            if (hashIdx !== -1) line = line.slice(0, hashIdx);
            line = line.trim();
            if (line && !seen.has(line)) {
                seen.add(line);
                titles.push(line);
            }
        }
        return titles;
    }

    function createModal() {
        if (document.getElementById('efficient-nuke-overlay')) return;
        resetState();
        injectStyles();

        mw.loader.load('mediawiki.diff.styles', 'text/css');

        const overlay = document.createElement('div');
        overlay.id = 'efficient-nuke-overlay';
        overlay.innerHTML = `
            <div id="efficient-nuke-modal">
                <div class="nuke-header">
                    <h3>MOSNUM 批量日期修复(Cite/Citation 精准版 + Diff审核 + 自动容错)</h3>
                    <button id="nuke-top-close-btn" class="nuke-mini-btn">✕ 关闭</button>
                </div>

                <div class="nuke-config-banner" id="nuke-config-banner"></div>

                <div class="nuke-controls-grid">
                    <div class="nuke-panel">
                        <div class="nuke-tabs">
                            <button type="button" class="nuke-tab-btn active" data-mode="contrib">用户贡献提取模式</button>
                            <button type="button" class="nuke-tab-btn" data-mode="list">列表批量转换模式</button>
                        </div>

                        <div id="nuke-panel-contrib">
                            <div class="nuke-field">
                                <label for="nuke-target-user">目标用户名</label>
                                <input type="text" id="nuke-target-user" value="Kiyoteru Awaji" />
                            </div>
                            <div class="nuke-inline-row">
                                <div class="nuke-field" style="flex:1;">
                                    <label for="nuke-namespace">命名空间 (如 0)</label>
                                    <input type="text" id="nuke-namespace" value="0" />
                                </div>
                                <div class="nuke-field" style="flex:1;">
                                    <label for="nuke-max-pages">最多页数 (0=不限)</label>
                                    <input type="number" id="nuke-max-pages" value="0" min="0" />
                                </div>
                            </div>
                            <div class="nuke-field">
                                <label for="nuke-uccontinue">断点游标 uccontinue(留空从头开始)</label>
                                <input type="text" id="nuke-uccontinue" placeholder="例如:20250101000000|12345678" />
                            </div>
                            <label class="nuke-check-label">
                                <input type="checkbox" id="nuke-top-only" />
                                仅提取最新编辑者页面 (ucshow=top,减轻千万级查询)
                            </label>
                        </div>

                        <div id="nuke-panel-list" style="display:none;">
                            <div class="nuke-field">
                                <label for="nuke-page-list">页面标题列表(每行一个,自动去重与剥离 [[ ]])</label>
                                <textarea id="nuke-page-list" placeholder="条目一&#10;[[条目二]]&#10;条目三#段落"></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="nuke-panel">
                        <div style="font-weight:bold; font-size:13px; margin-bottom:6px; border-bottom:1px solid #eaecf0; padding-bottom:4px;">
                            转换开关、冷却调节与安全选项
                        </div>
                        <label class="nuke-check-label">
                            <input type="checkbox" id="nuke-opt-zhjp" ${CONFIG.defaultEnableZhJp ? 'checked' : ''} />
                            <strong>中文 / 日文日期修复</strong>(Cite 内 YYYY年M月D日 → YYYY-MM-DD)
                        </label>
                        <label class="nuke-check-label">
                            <input type="checkbox" id="nuke-opt-en" ${CONFIG.defaultEnableEn ? 'checked' : ''} />
                            <strong>英文日期修复</strong>(按需加载 MOSNUM_utils.js)
                        </label>

                        <div class="nuke-inline-row" style="margin-top:6px;">
                            <div class="nuke-field" style="flex:1; margin-bottom:2px;">
                                <label for="nuke-edit-delay">写入冷却 (ms)</label>
                                <input type="number" id="nuke-edit-delay" value="${CONFIG.editDelay}" min="0" step="100" />
                            </div>
                            <div class="nuke-field" style="flex:1; margin-bottom:2px;">
                                <label for="nuke-read-delay">读取冷却 (ms)</label>
                                <input type="number" id="nuke-read-delay" value="${CONFIG.readDelay}" min="0" step="50" />
                            </div>
                        </div>

                        <div class="nuke-safety-box">
                            <label class="nuke-check-label">
                                <input type="checkbox" id="nuke-opt-review" ${CONFIG.defaultReviewMode ? 'checked' : ''} />
                                【安全选项】开启人工审核模式(保存前显示 Diff 对比,人工确认通过后才提交)
                            </label>
                        </div>

                        <div class="nuke-deadcode-note">
                            死代码无条件清理:始终移除 Cite 内的 <code>|和書</code>、<code>|洋書</code>、<code>|df=</code> 与页面中的 <code>{{use dmy/mdy dates}}</code>。
                        </div>
                    </div>
                </div>

                <div id="nuke-progress-wrapper">
                    <div id="nuke-progress-bar"></div>
                </div>

                <div id="nuke-counter-bar">
                    <div class="nuke-counter-item">已发现<span class="nuke-counter-val" id="val-total">0</span></div>
                    <div class="nuke-counter-item">队列待处理<span class="nuke-counter-val" id="val-queue" style="color:#6610f2;">0</span></div>
                    <div class="nuke-counter-item">已修正<span class="nuke-counter-val" id="val-success" style="color:#00af89;">0</span></div>
                    <div class="nuke-counter-item">无改动跳过<span class="nuke-counter-val" id="val-skip" style="color:#72777d;">0</span></div>
                    <div class="nuke-counter-item">失败/不存在<span class="nuke-counter-val" id="val-fail" style="color:#d33;">0</span></div>
                </div>

                <div id="nuke-review-panel">
                    <div class="nuke-review-header">
                        <div id="nuke-review-title" style="font-weight:bold;">待审核页面</div>
                        <div class="nuke-review-actions">
                            <button type="button" id="nuke-review-approve">✓ 通过并保存</button>
                            <button type="button" id="nuke-review-skip">✗ 跳过此页</button>
                        </div>
                    </div>
                    <div id="nuke-review-diff-body"></div>
                </div>

                <div class="nuke-log-toolbar">
                    <label class="nuke-check-label" style="margin:0;">
                        <input type="checkbox" id="nuke-hide-skip" />
                        仅显示改动、异常与错误(隐藏无改动条目)
                    </label>
                    <div class="nuke-inline-row">
                        <button type="button" id="nuke-export-log-btn" class="nuke-mini-btn">导出日志 (.txt)</button>
                        <button type="button" id="nuke-clear-log-btn" class="nuke-mini-btn">清空日志</button>
                    </div>
                </div>

                <ul id="efficient-nuke-log">
                    <li class="log-info">准备就绪。红色“人工审核模式”安全选项已默认勾选,确认配置后可开始运行。</li>
                </ul>

                <div class="nuke-buttons">
                    <button id="nuke-start-btn">开始执行</button>
                    <button id="nuke-pause-btn" style="background-color:#dc3545; display:none;">暂停</button>
                    <button id="nuke-close-btn" style="background-color:#72777d;">关闭并停止</button>
                </div>
            </div>
        `;
        document.body.appendChild(overlay);
        applyResponsiveModalSize();
        window.addEventListener('resize', applyResponsiveModalSize);

        const syncOptionsFromUI = () => {
            state.enableZhJp = document.getElementById('nuke-opt-zhjp').checked;
            state.enableEn = document.getElementById('nuke-opt-en').checked;
            state.reviewMode = document.getElementById('nuke-opt-review').checked;
            const eDelay = parseInt(document.getElementById('nuke-edit-delay').value, 10);
            const rDelay = parseInt(document.getElementById('nuke-read-delay').value, 10);
            state.editDelay = (!isNaN(eDelay) && eDelay >= 0) ? eDelay : CONFIG.editDelay;
            state.readDelay = (!isNaN(rDelay) && rDelay >= 0) ? rDelay : CONFIG.readDelay;
            updateConfigBanner();
        };
        syncOptionsFromUI();

        overlay.querySelectorAll('.nuke-tab-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                if (state.isRunning) return;
                overlay.querySelectorAll('.nuke-tab-btn').forEach(b => b.classList.remove('active'));
                btn.classList.add('active');
                state.mode = btn.dataset.mode;
                document.getElementById('nuke-panel-contrib').style.display = state.mode === 'contrib' ? 'block' : 'none';
                document.getElementById('nuke-panel-list').style.display = state.mode === 'list' ? 'block' : 'none';
                updateConfigBanner();
            });
        });

        ['nuke-opt-zhjp', 'nuke-opt-en', 'nuke-opt-review', 'nuke-edit-delay', 'nuke-read-delay'].forEach(id => {
            document.getElementById(id).addEventListener('input', syncOptionsFromUI);
            document.getElementById(id).addEventListener('change', syncOptionsFromUI);
        });

        document.getElementById('nuke-review-approve').addEventListener('click', () => {
            const job = state.currentReviewJob;
            if (!job) return;
            state.currentReviewJob = null;
            closeReviewPane();
            appendLog(`[审核通过-排队写入] ${job.title}`, 'info');
            state.editQueue.push(job);
            updateCounters();
            schedulePipeline();
        });

        document.getElementById('nuke-review-skip').addEventListener('click', () => {
            const job = state.currentReviewJob;
            if (!job) return;
            state.currentReviewJob = null;
            closeReviewPane();
            appendLog(`[审核跳过] ${job.title}`, 'skip');
            state.skipCount++;
            state.totalProcessed++;
            updateCounters();
            schedulePipeline();
        });

        document.getElementById('nuke-hide-skip').addEventListener('change', (e) => {
            document.getElementById('efficient-nuke-log').classList.toggle('hide-skip', e.target.checked);
        });
        document.getElementById('nuke-clear-log-btn').addEventListener('click', () => {
            document.getElementById('efficient-nuke-log').innerHTML = '';
            state.rawLogHistory = [];
        });
        document.getElementById('nuke-export-log-btn').addEventListener('click', () => {
            const blob = new Blob([state.rawLogHistory.join('\n')], { type: 'text/plain;charset=utf-8' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `mosnum-mass-log-${Date.now()}.txt`;
            a.click();
            URL.revokeObjectURL(url);
        });

        const closeAndAbort = () => {
            state.isAborted = true;
            state.isRunning = false;
            window.removeEventListener('resize', applyResponsiveModalSize);
            overlay.remove();
        };
        document.getElementById('nuke-close-btn').addEventListener('click', closeAndAbort);
        document.getElementById('nuke-top-close-btn').addEventListener('click', closeAndAbort);

        document.getElementById('nuke-pause-btn').addEventListener('click', () => {
            const btn = document.getElementById('nuke-pause-btn');
            if (!state.isPaused) {
                state.isPaused = true;
                btn.textContent = '继续';
                btn.style.backgroundColor = '#00af89';
                appendLog('队列已手动暂停。', 'info');
            } else {
                state.isPaused = false;
                state.consecutiveErrors = 0;
                btn.textContent = '暂停';
                btn.style.backgroundColor = '#dc3545';
                appendLog('已恢复执行(连续异常计数已归零)...', 'info');
                updateCounters();
                schedulePipeline();
            }
        });

        document.getElementById('nuke-start-btn').addEventListener('click', () => {
            const currentMode = state.mode;
            resetState();
            state.mode = currentMode;
            syncOptionsFromUI();
            closeReviewPane();

            if (!state.enableZhJp && !state.enableEn) {
                appendLog('未勾选日期转换,将仅执行死代码固定清理(|和書/|洋書/|df=/{{use dmy/mdy dates}})。', 'warn');
            }

            if (state.mode === 'contrib') {
                state.targetUser = document.getElementById('nuke-target-user').value.trim();
                if (!state.targetUser) {
                    appendLog('目标用户名不能为空!', 'fail');
                    return;
                }
                state.namespace = document.getElementById('nuke-namespace').value.trim() || '0';
                state.maxPages = parseInt(document.getElementById('nuke-max-pages').value, 10) || 0;
                state.uccontinue = document.getElementById('nuke-uccontinue').value.trim();
                state.topOnly = document.getElementById('nuke-top-only').checked;
            } else {
                const titles = parseListInput(document.getElementById('nuke-page-list').value);
                if (titles.length === 0) {
                    appendLog('页面列表不能为空!', 'fail');
                    return;
                }
                titles.forEach(t => {
                    state.seenTitles.add(t);
                    state.pendingQueue.push(t);
                });
                state.totalDiscovered = titles.length;
                appendLog(`已导入列表,共 ${titles.length} 个去重页面。`, 'info');
            }

            const startBtn = document.getElementById('nuke-start-btn');
            const pauseBtn = document.getElementById('nuke-pause-btn');
            startBtn.style.display = 'none';
            pauseBtn.style.display = 'block';
            pauseBtn.textContent = '暂停';
            pauseBtn.style.backgroundColor = '#dc3545';

            state.isRunning = true;
            updateCounters();

            if (state.enableEn && !enDependencyLoaded) {
                appendLog('已勾选英文模式,正在按需加载 MOSNUM_utils.js...', 'info');
                $.when(...dependencies.map(url => $.ajax(url, { dataType: 'script', cache: true })))
                    .then(() => {
                        enDependencyLoaded = true;
                        appendLog('MOSNUM_utils.js 加载成功,启动流水线...', 'info');
                        schedulePipeline();
                    })
                    .fail(() => {
                        state.isRunning = false;
                        startBtn.style.display = 'block';
                        pauseBtn.style.display = 'none';
                        appendLog('错误:远程依赖加载失败,请检查网络或取消勾选英文模式。', 'fail');
                    });
            } else {
                appendLog('启动流水线...', 'info');
                schedulePipeline();
            }
        });
    }

    // 在左侧“工具”栏生成触发入口
    mw.loader.using(['mediawiki.api', 'mediawiki.util']).then(function () {
        $(function () {
            const portlet = document.getElementById('p-tb');
            if (!portlet) return;
            const ul = portlet.querySelector('ul');
            if (!ul) return;

            const li = document.createElement('li');
            li.id = 't-mosnum-batch-nuke';
            li.innerHTML = '<span id="nuke-launch-link">批量修复MOSNUM日期</span>';
            ul.appendChild(li);

            li.addEventListener('click', createModal);
        });
    });
})();