跳到正文

科技·工程

洛谷代码对比器 1.0

wanglongye约 83 分钟
原文

这是 2026年4月28日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

用 AI 做的,用于实现类似于 CF 的代码对比功能,不一定没有问题。请先安装篡改猴再使用。链接自己去搜。

提示:请不要随意展开,这玩意 4141 KB,1.41.4k 行
C++
// ==UserScript==
// @name         洛谷代码对比
// @namespace    luogu-code-diff
// @version      1.3.0
// @description  在洛谷记录详情页添加代码对比功能
// @match        https://www.luogu.com.cn/record/*
// @match        https://www.luogu.com.cn/recordlist*
// @grant        GM_addStyle
// @run-at       document-idle
// @license      MIT
// ==/UserScript==

(function () {
  'use strict';

  const _unsafeWindow = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;

  // ======================== 常量配置 ========================
  const LUOGU_BASE = 'https://www.luogu.com.cn';
  const COLORS = {
    light: {
      addedBg: '#e6ffed',
      addedLineNum: '#22863a',
      addedText: '#24292e',
      removedBg: '#ffeef0',
      removedLineNum: '#cb2431',
      removedText: '#24292e',
      unchangedBg: '#ffffff',
      unchangedText: '#24292e',
      lineNumText: '#959da5',
      lineNumBg: '#f6f8fa',
      border: '#e1e4e8',
      modalBg: '#ffffff',
      overlayBg: 'rgba(0, 0, 0, 0.5)',
    },
    dark: {
      addedBg: '#1b3a1f',
      addedLineNum: '#3fb950',
      addedText: '#e6edf3',
      removedBg: '#3d1a1a',
      removedLineNum: '#f85149',
      removedText: '#e6edf3',
      unchangedBg: '#0d1117',
      unchangedText: '#e6edf3',
      lineNumText: '#484f58',
      lineNumBg: '#161b22',
      border: '#30363d',
      modalBg: '#161b22',
      overlayBg: 'rgba(0, 0, 0, 0.7)',
    },
  };

  // ======================== 用户设置 ========================

  const SETTINGS_KEY = 'lg-diff-settings';
  const DEFAULT_SETTINGS = {
    fontSize: 13,    // 字体大小 px
    lineHeight: 1.5, // 行间距倍数(1.5 = 1行代码 + 0.5行空行)
  };

  /** 加载用户设置 */
  function loadSettings() {
    try {
      const raw = localStorage.getItem(SETTINGS_KEY);
      if (raw) {
        const parsed = JSON.parse(raw);
        return { ...DEFAULT_SETTINGS, ...parsed };
      }
    } catch (e) {
      console.warn('[洛谷代码对比] 读取设置失败:', e);
    }
    return { ...DEFAULT_SETTINGS };
  }

  /** 保存用户设置 */
  function saveSettings(settings) {
    try {
      localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
    } catch (e) {
      console.warn('[洛谷代码对比] 保存设置失败:', e);
    }
  }

  /** 应用设置到代码区域 */
  function applyCodeSettings(codeEl, settings) {
    if (!codeEl) return;
    codeEl.style.fontSize = settings.fontSize + 'px';
    codeEl.style.lineHeight = String(settings.lineHeight);
    // 同步行号区域
    const lineNums = codeEl.querySelectorAll('.lg-diff-ln-old, .lg-diff-ln-new');
    lineNums.forEach(el => {
      el.style.fontSize = Math.max(settings.fontSize - 1, 10) + 'px';
      el.style.lineHeight = String(settings.lineHeight);
    });
  }

  // ======================== 工具函数 ========================

  /** 判断当前是否为暗色模式 */
  function isDarkMode() {
    return (
      document.documentElement.getAttribute('data-theme') === 'dark' ||
      document.body?.getAttribute('data-theme') === 'dark' ||
      window.matchMedia('(prefers-color-scheme: dark)').matches
    );
  }

  /** 获取当前配色方案 */
  function getColors() {
    return isDarkMode() ? COLORS.dark : COLORS.light;
  }

  /** HTML 转义 */
  function escapeHtml(str) {
    if (str === null || str === undefined) return '';
    return String(str)
      .replace(/&/g, '&')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;');
  }

  /** 从当前 URL 提取记录 ID */
  function getRecordIdFromUrl() {
    const match = window.location.pathname.match(/\/record\/(\d+)/);
    return match ? match[1] : null;
  }

  /** 发起洛谷 API 请求(同源 fetch,自动携带 Cookie)
   *  使用 _contentOnly 参数让洛谷返回 JSON 数据而非 HTML
   */
  function fetchLuogu(url) {
    // 构建带 _contentOnly 参数的 URL
    const fullUrl = url.startsWith('http') ? url : LUOGU_BASE + url;
    const separator = fullUrl.includes('?') ? '&' : '?';
    const jsonUrl = `${fullUrl}${separator}_contentOnly=1`;

    return fetch(jsonUrl, {
      method: 'GET',
      credentials: 'same-origin',
      headers: {
        Accept: 'application/json',
      },
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error(`HTTP ${response.status}: ${response.statusText}`);
        }
        return response.json();
      })
      .catch((e) => {
        throw new Error(`请求失败: ${e.message}`);
      });
  }

  /** 从洛谷页面响应中提取数据
   *  洛谷 _contentOnly 返回格式:
   *  { code: 200, currentData: {...}, currentTemplate: "...", currentUser: {...} }
   */
  function extractData(response) {
    // 检查返回码
    if (response.code !== undefined && response.code !== 200) {
      throw new Error(`洛谷返回错误码: ${response.code}`);
    }

    // _contentOnly 格式:数据在 currentData 中
    if (response.currentData) return response.currentData;

    // Lentille 格式:数据在 data 中
    if (response.data) return response.data;

    // 记录详情可能直接在顶层
    if (response.record) return response;

    // 记录列表的 records 字段
    if (response.records) return response;

    console.log('[洛谷代码对比] 未识别的响应格式:', response);
    throw new Error('无法从响应中提取数据');
  }

  // ======================== Diff 算法 ========================

  /**
   * 基于行级的 LCS diff 算法
   * 返回 [{type: 'added'|'removed'|'unchanged', oldLine, newLine, content}]
   */
  function lineDiff(oldLines, newLines) {
    const m = oldLines.length;
    const n = newLines.length;

    // 构建 LCS DP 表
    const dp = new Array(m + 1);
    for (let i = 0; i <= m; i++) {
      dp[i] = new Array(n + 1).fill(0);
    }

    for (let i = 1; i <= m; i++) {
      for (let j = 1; j <= n; j++) {
        if (oldLines[i - 1] === newLines[j - 1]) {
          dp[i][j] = dp[i - 1][j - 1] + 1;
        } else {
          dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);
        }
      }
    }

    // 回溯 diff 结果
    const result = [];
    let i = m,
      j = n;
    const rawDiffs = [];

    while (i > 0 || j > 0) {
      if (i > 0 && j > 0 && oldLines[i - 1] === newLines[j - 1]) {
        rawDiffs.push({ type: 'unchanged', oldIdx: i - 1, newIdx: j - 1, content: oldLines[i - 1] });
        i--;
        j--;
      } else if (j > 0 && (i === 0 || dp[i][j - 1] >= dp[i - 1][j])) {
        rawDiffs.push({ type: 'added', newIdx: j - 1, content: newLines[j - 1] });
        j--;
      } else {
        rawDiffs.push({ type: 'removed', oldIdx: i - 1, content: oldLines[i - 1] });
        i--;
      }
    }

    rawDiffs.reverse();

    // 合并相邻的删除和新增为"修改"
    const merged = [];
    let k = 0;
    while (k < rawDiffs.length) {
      if (
        rawDiffs[k].type === 'removed' &&
        k + 1 < rawDiffs.length &&
        rawDiffs[k + 1].type === 'added'
      ) {
        // 收集连续的 removed + added 对
        const removedGroup = [];
        const addedGroup = [];
        while (
          k < rawDiffs.length &&
          (rawDiffs[k].type === 'removed' ||
            (rawDiffs[k].type === 'added' && removedGroup.length > 0))
        ) {
          if (rawDiffs[k].type === 'removed') {
            removedGroup.push(rawDiffs[k]);
          } else {
            addedGroup.push(rawDiffs[k]);
          }
          k++;
        }
        // 先输出删除行,再输出新增行
        for (const item of removedGroup) {
          merged.push({ ...item, pairedWithAdd: true });
        }
        for (const item of addedGroup) {
          merged.push({ ...item, pairedWithRemove: true });
        }
      } else {
        merged.push(rawDiffs[k]);
        k++;
      }
    }

    return merged;
  }

  // ======================== UI 组件 ========================

  /** 创建加载遮罩 */
  function createLoadingOverlay(message) {
    const overlay = document.createElement('div');
    overlay.id = 'lg-diff-loading';
    overlay.style.cssText = `
      position: fixed; top: 0; left: 0; right: 0; bottom: 0;
      background: rgba(0,0,0,0.5); z-index: 100000;
      display: flex; align-items: center; justify-content: center;
      flex-direction: column; gap: 16px;
    `;
    overlay.innerHTML = `
      <div style="
        background: ${getColors().modalBg}; border-radius: 12px;
        padding: 32px 48px; text-align: center;
        box-shadow: 0 8px 32px rgba(0,0,0,0.3);
        color: ${isDarkMode() ? '#e6edf3' : '#24292e'};
        font-size: 16px;
      ">
        <div class="lg-diff-spinner" style="
          width: 36px; height: 36px; margin: 0 auto 16px;
          border: 3px solid ${isDarkMode() ? '#30363d' : '#e1e4e8'};
          border-top-color: #3498db; border-radius: 50%;
          animation: lg-diff-spin 0.8s linear infinite;
        "></div>
        <div>${escapeHtml(message)}</div>
      </div>
    `;
    document.body.appendChild(overlay);
    return overlay;
  }

  /** 移除加载遮罩 */
  function removeLoadingOverlay() {
    const overlay = document.getElementById('lg-diff-loading');
    if (overlay) overlay.remove();
  }

  /** 渲染 Diff 结果到模态框 */
  function showDiffModal(oldCode, newCode, oldRecordId, newRecordId) {
    const colors = getColors();
    const dark = isDarkMode();

    // 执行 diff(确保 sourceCode 是字符串)
    const oldLines = String(oldCode || '').split('\n');
    const newLines = String(newCode || '').split('\n');
    const diffs = lineDiff(oldLines, newLines);

    // 构建代码行 HTML
    let codeHtml = '';
    let oldLineNum = 0;
    let newLineNum = 0;

    for (const diff of diffs) {
      if (diff.type === 'unchanged') {
        oldLineNum++;
        newLineNum++;
        codeHtml += '<div class="lg-diff-line lg-diff-unchanged">' +
          '<span class="lg-diff-ln-old">' + oldLineNum + '</span>' +
          '<span class="lg-diff-ln-new">' + newLineNum + '</span>' +
          '<span class="lg-diff-content">' + escapeHtml(diff.content) + '</span>' +
          '</div>';
      } else if (diff.type === 'removed') {
        oldLineNum++;
        codeHtml += '<div class="lg-diff-line lg-diff-removed">' +
          '<span class="lg-diff-ln-old">' + oldLineNum + '</span>' +
          '<span class="lg-diff-ln-new"></span>' +
          '<span class="lg-diff-marker">-</span>' +
          '<span class="lg-diff-content">' + escapeHtml(diff.content) + '</span>' +
          '</div>';
      } else if (diff.type === 'added') {
        newLineNum++;
        codeHtml += '<div class="lg-diff-line lg-diff-added">' +
          '<span class="lg-diff-ln-old"></span>' +
          '<span class="lg-diff-ln-new">' + newLineNum + '</span>' +
          '<span class="lg-diff-marker">+</span>' +
          '<span class="lg-diff-content">' + escapeHtml(diff.content) + '</span>' +
          '</div>';
      }
    }

    // 统计变更
    const addedCount = diffs.filter((d) => d.type === 'added').length;
    const removedCount = diffs.filter((d) => d.type === 'removed').length;

    // 加载用户设置
    const settings = loadSettings();

    // 创建模态框
    const overlay = document.createElement('div');
    overlay.id = 'lg-diff-modal-overlay';
    overlay.innerHTML = `
      <div class="lg-diff-modal ${dark ? 'lg-diff-dark' : 'lg-diff-light'}">
        <div class="lg-diff-header">
          <div class="lg-diff-title">
            <span class="lg-diff-title-icon">📋</span>
            代码对比
          </div>
          <div class="lg-diff-ids">
            <a href="${LUOGU_BASE}/record/${escapeHtml(oldRecordId)}" target="_blank" class="lg-diff-record-link old">#${escapeHtml(String(oldRecordId))}</a>
            <span class="lg-diff-arrow">→</span>
            <a href="${LUOGU_BASE}/record/${escapeHtml(newRecordId)}" target="_blank" class="lg-diff-record-link new">#${escapeHtml(String(newRecordId))}</a>
          </div>
          <div class="lg-diff-stats">
            <span class="lg-diff-stat-added">+${addedCount} 行</span>
            <span class="lg-diff-stat-removed">-${removedCount} 行</span>
          </div>
          <button class="lg-diff-close" title="关闭">✕</button>
        </div>
        <div class="lg-diff-body">
          <div class="lg-diff-code" id="lg-diff-code-area">${codeHtml}</div>
        </div>
        <div class="lg-diff-settings-bar" id="lg-diff-settings-bar">
          <span class="lg-diff-settings-label">字号</span>
          <button class="lg-diff-settings-btn" id="lg-diff-font-dec" title="缩小字体">A−</button>
          <span class="lg-diff-settings-value" id="lg-diff-font-value">${settings.fontSize}px</span>
          <button class="lg-diff-settings-btn" id="lg-diff-font-inc" title="放大字体">A+</button>
          <span class="lg-diff-settings-divider">|</span>
          <span class="lg-diff-settings-label">行距</span>
          <button class="lg-diff-settings-btn" id="lg-diff-lh-dec" title="缩小行距">−</button>
          <span class="lg-diff-settings-value" id="lg-diff-lh-value">${settings.lineHeight}x</span>
          <button class="lg-diff-settings-btn" id="lg-diff-lh-inc" title="放大行距">+</button>
        </div>
        <div class="lg-diff-footer">
          <button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-custom-compare">对比其他提交</button>
          <button class="lg-diff-btn lg-diff-btn-primary" id="lg-diff-close-btn">关闭</button>
        </div>
      </div>
    `;

    document.body.appendChild(overlay);

    // 应用用户设置
    const codeArea = overlay.querySelector('#lg-diff-code-area');
    applyCodeSettings(codeArea, settings);

    // 字体大小调节
    let currentSettings = { ...settings };

    const fontDecBtn = overlay.querySelector('#lg-diff-font-dec');
    const fontIncBtn = overlay.querySelector('#lg-diff-font-inc');
    const fontValueEl = overlay.querySelector('#lg-diff-font-value');
    const lhDecBtn = overlay.querySelector('#lg-diff-lh-dec');
    const lhIncBtn = overlay.querySelector('#lg-diff-lh-inc');
    const lhValueEl = overlay.querySelector('#lg-diff-lh-value');

    fontDecBtn.addEventListener('click', () => {
      currentSettings.fontSize = Math.max(currentSettings.fontSize - 1, 8);
      fontValueEl.textContent = currentSettings.fontSize + 'px';
      applyCodeSettings(codeArea, currentSettings);
      saveSettings(currentSettings);
    });

    fontIncBtn.addEventListener('click', () => {
      currentSettings.fontSize = Math.min(currentSettings.fontSize + 1, 28);
      fontValueEl.textContent = currentSettings.fontSize + 'px';
      applyCodeSettings(codeArea, currentSettings);
      saveSettings(currentSettings);
    });

    lhDecBtn.addEventListener('click', () => {
      currentSettings.lineHeight = Math.max(+(currentSettings.lineHeight - 0.1).toFixed(1), 1.0);
      lhValueEl.textContent = currentSettings.lineHeight + 'x';
      applyCodeSettings(codeArea, currentSettings);
      saveSettings(currentSettings);
    });

    lhIncBtn.addEventListener('click', () => {
      currentSettings.lineHeight = Math.min(+(currentSettings.lineHeight + 0.1).toFixed(1), 3.0);
      lhValueEl.textContent = currentSettings.lineHeight + 'x';
      applyCodeSettings(codeArea, currentSettings);
      saveSettings(currentSettings);
    });

    // 事件绑定
    const close = () => overlay.remove();
    overlay.querySelector('.lg-diff-close').addEventListener('click', close);
    overlay.querySelector('#lg-diff-close-btn').addEventListener('click', close);
    overlay.addEventListener('click', (e) => {
      if (e.target === overlay) close();
    });

    // 自定义对比
    overlay.querySelector('#lg-diff-custom-compare').addEventListener('click', () => {
      close();
      promptCustomCompare(newRecordId);
    });

    // ESC 关闭
    const escHandler = (e) => {
      if (e.key === 'Escape') {
        close();
        document.removeEventListener('keydown', escHandler);
      }
    };
    document.addEventListener('keydown', escHandler);
  }

  /** 提示用户输入自定义提交 ID */
  function promptCustomCompare(currentRecordId) {
    const existing = document.getElementById('lg-diff-custom-dialog');
    if (existing) existing.remove();

    const dark = isDarkMode();
    const colors = getColors();

    const dialog = document.createElement('div');
    dialog.id = 'lg-diff-custom-dialog';
    dialog.innerHTML = `
      <div class="lg-diff-modal ${dark ? 'lg-diff-dark' : 'lg-diff-light'}" style="max-width: 480px;">
        <div class="lg-diff-header">
          <div class="lg-diff-title">输入对比提交 ID</div>
          <button class="lg-diff-close" title="关闭">✕</button>
        </div>
        <div class="lg-diff-body" style="padding: 24px;">
          <p style="margin: 0 0 16px; color: ${dark ? '#8b949e' : '#586069'}; font-size: 14px;">
            输入要与当前提交 (#${escapeHtml(String(currentRecordId))}) 对比的提交记录 ID
          </p>
          <input type="text" id="lg-diff-custom-id" placeholder="例如 12345678" style="
            width: 100%; padding: 10px 14px; border-radius: 8px;
            border: 1px solid ${dark ? '#30363d' : '#e1e4e8'};
            background: ${dark ? '#0d1117' : '#ffffff'};
            color: ${dark ? '#e6edf3' : '#24292e'};
            font-size: 15px; outline: none; box-sizing: border-box;
          " />
          <div id="lg-diff-custom-error" style="color: #cb2431; font-size: 13px; margin-top: 8px; display: none;"></div>
        </div>
        <div class="lg-diff-footer">
          <button class="lg-diff-btn lg-diff-btn-secondary" id="lg-diff-custom-cancel">取消</button>
          <button class="lg-diff-btn lg-diff-btn-primary" id="lg-diff-custom-ok">开始对比</button>
        </div>
      </div>
    `;

    document.body.appendChild(dialog);

    const closeDialog = () => dialog.remove();
    dialog.querySelector('.lg-diff-close').addEventListener('click', closeDialog);
    dialog.querySelector('#lg-diff-custom-cancel').addEventListener('click', closeDialog);
    dialog.addEventListener('click', (e) => {
      if (e.target === dialog) closeDialog();
    });

    const input = dialog.querySelector('#lg-diff-custom-id');
    input.focus();

    const doCompare = async () => {
      const targetId = input.value.trim();
      if (!targetId || !/^\d+$/.test(targetId)) {
        const errEl = dialog.querySelector('#lg-diff-custom-error');
        errEl.textContent = '请输入有效的数字 ID';
        errEl.style.display = 'block';
        return;
      }
      closeDialog();
      await runCompare(currentRecordId, targetId);
    };

    dialog.querySelector('#lg-diff-custom-ok').addEventListener('click', doCompare);
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') doCompare();
    });
  }

  // ======================== 核心逻辑 ========================

  /** 获取记录详情(包含源代码)
   *  请求 /record/{id}?_contentOnly=1
   *  返回格式: { code: 200, currentData: { record: RecordDetails, ... } }
   */
  async function fetchRecordDetail(recordId) {
    const url = `${LUOGU_BASE}/record/${recordId}`;
    const response = await fetchLuogu(url);
    console.log('[洛谷代码对比] 记录详情响应:', response);
    const data = extractData(response);

    // _contentOnly 返回的数据在 currentData 中,record 直接在 data 下
    if (!data.record) {
      console.error('[洛谷代码对比] 响应中没有 record 字段,响应数据:', JSON.stringify(data).slice(0, 500));
      throw new Error('无法获取记录信息(response 中缺少 record 字段)');
    }

    return data.record;
  }

  /** 获取提交记录列表
   *  请求 /record/list?pid=P1001&user=123&_contentOnly=1
   *  返回格式: { code: 200, currentData: { records: [...], ... } }
   *  注意: records 可能是分页对象 { result: [...], count, perPage } 或直接数组
   */
  async function fetchRecordList(params) {
    const query = new URLSearchParams();
    if (params.pid) query.set('pid', params.pid);
    if (params.user) query.set('user', params.user);
    if (params.page) query.set('page', String(params.page));

    const url = `${LUOGU_BASE}/record/list?${query.toString()}`;
    const response = await fetchLuogu(url);
    console.log('[洛谷代码对比] 记录列表响应:', response);
    const data = extractData(response);

    console.log('[洛谷代码对比] 记录列表 data.records 类型:', typeof data.records, Array.isArray(data.records), JSON.stringify(data.records).slice(0, 300));

    //洛谷 records 字段可能是:
    // 1. 直接数组: [record1, record2, ...]
    // 2. 分页对象: { result: [...], count: N, perPage: M }
    // 3. 其他嵌套结构: { records: [...] }(较少见但防御性处理)
    let records = data.records;

    if (Array.isArray(records)) {
      // 直接数组,无需处理
      return records;
    }

    if (records && typeof records === 'object') {
      // 分页对象:result 字段包含实际数组
      if (Array.isArray(records.result)) {
        console.log('[洛谷代码对比] records 是分页对象,使用 result 字段');
        return records.result;
      }
      // 嵌套 records 字段
      if (Array.isArray(records.records)) {
        console.log('[洛谷代码对比] records 是嵌套对象,使用 records.records 字段');
        return records.records;
      }
      // records 对象的 values 或 data 字段
      if (Array.isArray(records.values)) {
        return records.values;
      }
      if (Array.isArray(records.data)) {
        return records.data;
      }
    }

    // records 为 null/undefined 或无法识别的结构
    console.error('[洛谷代码对比] 无法识别 records 格式:', records);
    return [];
  }

  /** 查找同一用户同一题目的上一次提交 */
  async function findPrevRecord(currentRecordId, pid, uid) {
    // 洛谷记录列表默认按时间倒序排列(最新的在前)
    // 遍历前两页查找
    for (let page = 1; page <= 2; page++) {
      const records = await fetchRecordList({ pid, user: String(uid), page });

      const currentIdx = records.findIndex((r) => String(r.id) === String(currentRecordId));

      if (currentIdx !== -1) {
        // 当前提交在本页找到,返回列表中它之后的第一个(即时间上更早的)
        if (currentIdx + 1 < records.length) {
          return records[currentIdx + 1];
        }
        // 当前提交在列表末尾,需要看下一页
        continue;
      }

      // 当前提交不在本页,如果当前页的记录提交时间都早于当前提交,
      // 则返回本页第一条(最新的早于当前的)
      if (records.length > 0) {
        // 检查本页是否有不是当前提交的记录
        for (const record of records) {
          if (String(record.id) !== String(currentRecordId)) {
            return record;
          }
        }
      }
    }

    throw new Error('未找到该题目的上一次提交记录');
  }

  /** 执行对比 */
  async function runCompare(currentRecordId, targetRecordId) {
    const loading = createLoadingOverlay('正在获取代码,请稍候...');

    try {
      let currentRecord;
      let targetRecord;

      // 优先从页面内嵌数据获取当前提交信息(零延迟)
      const pageData = _unsafeWindow._feInjection?.currentData;
      if (pageData?.record) {
        currentRecord = pageData.record;
        console.log('[洛谷代码对比] 从页面内嵌数据获取当前记录成功');
      }

      if (targetRecordId) {
        // 有指定的对比 ID
        if (!currentRecord) {
          updateLoadingMessage(loading, '正在获取当前提交代码...');
          currentRecord = await fetchRecordDetail(currentRecordId);
        }

        updateLoadingMessage(loading, '正在获取对比提交代码...');
        targetRecord = await fetchRecordDetail(targetRecordId);
      } else {
        // 自动查找上一次提交
        if (!currentRecord) {
          updateLoadingMessage(loading, '正在获取当前提交信息...');
          currentRecord = await fetchRecordDetail(currentRecordId);
        }

        // 洛谷 problem 对象结构:{ pid: "P1001", title: "...", ... }
        // 也可能嵌套在其他结构中
        const problem = currentRecord.problem;
        const pid =
          problem?.pid ||
          problem?.id ||
          problem?.problemId ||
          (typeof problem === 'string' ? problem : null);

        // 用户 ID 可能直接在 record 层级或 user 对象中
        const uid = currentRecord.user?.uid || currentRecord.uid;

        if (!pid) throw new Error('无法获取题目 ID(problem 字段缺失)');
        if (!uid) throw new Error('无法获取用户信息(可能需要登录)');

        updateLoadingMessage(loading, '正在查找上一次提交记录...');
        const prevRecordBase = await findPrevRecord(currentRecordId, pid, uid);

        updateLoadingMessage(loading, '正在获取上一次提交代码...');
        targetRecord = await fetchRecordDetail(prevRecordBase.id);
      }

      // 检查源代码是否可访问
      if (!currentRecord.sourceCode && currentRecord.sourceCode !== '') {
        throw new Error('当前提交的代码不可访问(可能是隐私设置)');
      }
      if (!targetRecord.sourceCode && targetRecord.sourceCode !== '') {
        throw new Error('对比提交的代码不可访问(可能是隐私设置)');
      }

      removeLoadingOverlay();

      // 展示 diff 结果(targetRecord 是旧代码,currentRecord 是新代码)
      showDiffModal(
        String(targetRecord.sourceCode ?? ''),
        String(currentRecord.sourceCode ?? ''),
        String(targetRecord.id),
        String(currentRecord.id)
      );
    } catch (err) {
      removeLoadingOverlay();
      showError(err.message);
    }
  }

  /** 更新加载提示文字 */
  function updateLoadingMessage(overlay, message) {
    const textEl = overlay.querySelector('div > div:last-child');
    if (textEl) textEl.textContent = message;
  }

  /** 显示错误提示 */
  function showError(message) {
    const dark = isDarkMode();
    const toast = document.createElement('div');
    toast.style.cssText = `
      position: fixed; top: 20px; left: 50%; transform: translateX(-50%);
      z-index: 200000; background: ${dark ? '#3d1a1a' : '#ffeef0'};
      color: ${dark ? '#f85149' : '#cb2431'}; padding: 12px 24px;
      border-radius: 8px; font-size: 14px; box-shadow: 0 4px 16px rgba(0,0,0,0.2);
      border: 1px solid ${dark ? '#f8514940' : '#cb243140'};
      max-width: 480px; text-align: center;
    `;
    toast.textContent = `❌ ${message}`;
    document.body.appendChild(toast);
    setTimeout(() => {
      toast.style.transition = 'opacity 0.3s';
      toast.style.opacity = '0';
      setTimeout(() => toast.remove(), 300);
    }, 4000);
  }

  // ======================== 按钮注入 ========================

  /** 注入对比按钮到页面 */
  function injectCompareButton() {
    // 避免重复注入
    if (document.getElementById('lg-diff-compare-btn')) return;

    const recordId = getRecordIdFromUrl();
    if (!recordId) return;

    // 查找合适的插入位置
    // 尝试多种选择器以适配不同版本的洛谷页面
    const insertTargets = [
      // 操作栏按钮区域
      '.header-actions',
      '.operation-panel',
      '.record-operations',
      // 代码区域旁
      '.markdown-renderer',
      // 通用信息区域
      '.card',
      '.main-container',
      // 更通用的选择器
      'main',
      '#main-content',
      '.content',
    ];

    let targetEl = null;
    for (const selector of insertTargets) {
      targetEl = document.querySelector(selector);
      if (targetEl) break;
    }

    // 如果找不到特定容器,尝试在页面顶部创建浮动按钮
    const btn = document.createElement('button');
    btn.id = 'lg-diff-compare-btn';
    btn.textContent = '⇄ 对比代码';
    btn.title = '与同题上一次提交进行代码对比';

    const dark = isDarkMode();
    btn.style.cssText = `
      position: fixed;
      bottom: 24px;
      right: 24px;
      z-index: 99999;
      padding: 12px 20px;
      border: none;
      border-radius: 24px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: #ffffff;
      font-size: 15px;
      font-weight: 600;
      cursor: pointer;
      box-shadow: 0 4px 16px rgba(102, 126, 234, 0.4);
      transition: all 0.2s ease;
      letter-spacing: 0.5px;
    `;

    // 悬停效果
    btn.addEventListener('mouseenter', () => {
      btn.style.transform = 'scale(1.05)';
      btn.style.boxShadow = '0 6px 24px rgba(102, 126, 234, 0.6)';
    });
    btn.addEventListener('mouseleave', () => {
      btn.style.transform = 'scale(1)';
      btn.style.boxShadow = '0 4px 16px rgba(102, 126, 234, 0.4)';
    });

    btn.addEventListener('click', async () => {
      btn.style.pointerEvents = 'none';
      btn.style.opacity = '0.6';
      try {
        await runCompare(recordId, null);
      } finally {
        btn.style.pointerEvents = 'auto';
        btn.style.opacity = '1';
      }
    });

    document.body.appendChild(btn);

    // 同时尝试在页面内注入一个次要按钮
    injectInlineButton(recordId);
  }

  /** 在页面内注入行内对比按钮 */
  function injectInlineButton(recordId) {
    // 尝试在代码块上方或操作区域添加按钮
    const codeBlock = document.querySelector('pre') || document.querySelector('code');
    if (!codeBlock) return;

    const container = document.createElement('div');
    container.style.cssText = `
      display: flex; gap: 8px; margin: 8px 0; align-items: center;
    `;

    const inlineBtn = document.createElement('button');
    inlineBtn.className = 'lg-diff-inline-btn';
    inlineBtn.textContent = '⇄ 与上次提交对比';
    inlineBtn.style.cssText = `
      padding: 6px 16px; border: 1px solid #667eea; border-radius: 6px;
      background: transparent; color: #667eea; font-size: 13px;
      cursor: pointer; transition: all 0.2s;
    `;
    inlineBtn.addEventListener('mouseenter', () => {
      inlineBtn.style.background = '#667eea';
      inlineBtn.style.color = '#fff';
    });
    inlineBtn.addEventListener('mouseleave', () => {
      inlineBtn.style.background = 'transparent';
      inlineBtn.style.color = '#667eea';
    });
    inlineBtn.addEventListener('click', async () => {
      inlineBtn.style.pointerEvents = 'none';
      try {
        await runCompare(recordId, null);
      } finally {
        inlineBtn.style.pointerEvents = 'auto';
      }
    });

    const customBtn = document.createElement('button');
    customBtn.className = 'lg-diff-inline-btn';
    customBtn.textContent = '⇄ 对比指定提交';
    customBtn.style.cssText = `
      padding: 6px 16px; border: 1px solid #8b5cf6; border-radius: 6px;
      background: transparent; color: #8b5cf6; font-size: 13px;
      cursor: pointer; transition: all 0.2s;
    `;
    customBtn.addEventListener('mouseenter', () => {
      customBtn.style.background = '#8b5cf6';
      customBtn.style.color = '#fff';
    });
    customBtn.addEventListener('mouseleave', () => {
      customBtn.style.background = 'transparent';
      customBtn.style.color = '#8b5cf6';
    });
    customBtn.addEventListener('click', () => {
      promptCustomCompare(recordId);
    });

    container.appendChild(inlineBtn);
    container.appendChild(customBtn);

    // 插入到代码块之前
    const preParent = codeBlock.closest('pre') || codeBlock.parentElement;
    if (preParent && preParent.parentElement) {
      preParent.parentElement.insertBefore(container, preParent);
    }
  }

  // ======================== 样式注入 ========================

  function injectStyles() {
    GM_addStyle(`
      /* 旋转动画 */
      @keyframes lg-diff-spin {
        to { transform: rotate(360deg); }
      }

      /* 模态框遮罩 */
      #lg-diff-modal-overlay,
      #lg-diff-custom-dialog {
        position: fixed;
        top: 0; left: 0; right: 0; bottom: 0;
        z-index: 150000;
        display: flex;
        align-items: center;
        justify-content: center;
        background: rgba(0, 0, 0, 0.5);
      }

      /* 模态框 */
      .lg-diff-modal {
        width: 90vw;
        max-width: 960px;
        max-height: 85vh;
        border-radius: 16px;
        overflow: hidden;
        display: flex;
        flex-direction: column;
        box-shadow: 0 16px 64px rgba(0, 0, 0, 0.3);
      }

      .lg-diff-modal.lg-diff-light {
        background: #ffffff;
      }

      .lg-diff-modal.lg-diff-dark {
        background: #161b22;
      }

      /* 头部 */
      .lg-diff-header {
        display: flex;
        align-items: center;
        gap: 16px;
        padding: 16px 24px;
        border-bottom: 1px solid;
      }

      .lg-diff-light .lg-diff-header {
        border-color: #e1e4e8;
        background: #f6f8fa;
      }

      .lg-diff-dark .lg-diff-header {
        border-color: #30363d;
        background: #0d1117;
      }

      .lg-diff-title {
        font-size: 18px;
        font-weight: 700;
        display: flex;
        align-items: center;
        gap: 8px;
      }

      .lg-diff-light .lg-diff-title { color: #24292e; }
      .lg-diff-dark .lg-diff-title { color: #e6edf3; }

      .lg-diff-title-icon {
        font-size: 20px;
      }

      .lg-diff-ids {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 14px;
      }

      .lg-diff-record-link {
        text-decoration: none;
        font-weight: 600;
        padding: 2px 8px;
        border-radius: 4px;
        transition: opacity 0.2s;
      }

      .lg-diff-record-link:hover { opacity: 0.8; }

      .lg-diff-record-link.old {
        color: #cb2431;
        background: #ffeef0;
      }

      .lg-diff-dark .lg-diff-record-link.old {
        color: #f85149;
        background: #3d1a1a;
      }

      .lg-diff-record-link.new {
        color: #22863a;
        background: #e6ffed;
      }

      .lg-diff-dark .lg-diff-record-link.new {
        color: #3fb950;
        background: #1b3a1f;
      }

      .lg-diff-arrow {
        color: #959da5;
        font-weight: 700;
      }

      .lg-diff-stats {
        margin-left: auto;
        display: flex;
        gap: 12px;
        font-size: 13px;
        font-weight: 600;
      }

      .lg-diff-stat-added { color: #22863a; }
      .lg-diff-stat-removed { color: #cb2431; }
      .lg-diff-dark .lg-diff-stat-added { color: #3fb950; }
      .lg-diff-dark .lg-diff-stat-removed { color: #f85149; }

      .lg-diff-close {
        width: 32px; height: 32px;
        border: none; border-radius: 8px;
        cursor: pointer; font-size: 18px;
        display: flex; align-items: center; justify-content: center;
        transition: background 0.2s;
      }

      .lg-diff-light .lg-diff-close {
        background: #f0f0f0; color: #586069;
      }

      .lg-diff-light .lg-diff-close:hover {
        background: #d0d0d0;
      }

      .lg-diff-dark .lg-diff-close {
        background: #21262d; color: #8b949e;
      }

      .lg-diff-dark .lg-diff-close:hover {
        background: #30363d;
      }

      /* 代码区域 */
      .lg-diff-body {
        flex: 1;
        overflow: auto;
        padding: 0;
      }

      .lg-diff-code {
        font-family: 'Cascadia Code', 'Fira Code', 'JetBrains Mono', 'Consolas', monospace;
        font-size: 13px;
        line-height: 1.5;
        white-space: pre;
      }

      /* 代码行 */
      .lg-diff-line {
        display: flex;
        min-height: 0;
      }

      .lg-diff-ln-old,
      .lg-diff-ln-new {
        display: inline-block;
        width: 48px;
        min-width: 48px;
        text-align: right;
        padding-right: 10px;
        user-select: none;
        font-size: 12px;
        line-height: 1.5;
      }

      .lg-diff-marker {
        display: inline-block;
        width: 20px;
        min-width: 20px;
        text-align: center;
        user-select: none;
        font-weight: 700;
      }

      .lg-diff-content {
        flex: 1;
        white-space: pre;
        padding-left: 8px;
      }

      /* 未变更行 */
      .lg-diff-unchanged {
        background: transparent;
      }

      .lg-diff-light .lg-diff-unchanged .lg-diff-ln-old,
      .lg-diff-light .lg-diff-unchanged .lg-diff-ln-new {
        color: #959da5;
        background: #f6f8fa;
      }

      .lg-diff-light .lg-diff-unchanged .lg-diff-content {
        color: #24292e;
      }

      .lg-diff-dark .lg-diff-unchanged .lg-diff-ln-old,
      .lg-diff-dark .lg-diff-unchanged .lg-diff-ln-new {
        color: #484f58;
        background: #161b22;
      }

      .lg-diff-dark .lg-diff-unchanged .lg-diff-content {
        color: #e6edf3;
      }

      /* 删除行 */
      .lg-diff-removed {
        background: #ffeef0;
      }

      .lg-diff-light .lg-diff-removed .lg-diff-ln-old {
        color: #cb2431;
        background: #f8d7da;
      }

      .lg-diff-light .lg-diff-removed .lg-diff-ln-new {
        background: #ffeef0;
      }

      .lg-diff-light .lg-diff-removed .lg-diff-marker {
        color: #cb2431;
      }

      .lg-diff-light .lg-diff-removed .lg-diff-content {
        color: #24292e;
      }

      .lg-diff-dark .lg-diff-removed {
        background: #3d1a1a;
      }

      .lg-diff-dark .lg-diff-removed .lg-diff-ln-old {
        color: #f85149;
        background: #4d2020;
      }

      .lg-diff-dark .lg-diff-removed .lg-diff-ln-new {
        background: #3d1a1a;
      }

      .lg-diff-dark .lg-diff-removed .lg-diff-marker {
        color: #f85149;
      }

      .lg-diff-dark .lg-diff-removed .lg-diff-content {
        color: #e6edf3;
      }

      /* 新增行 */
      .lg-diff-added {
        background: #e6ffed;
      }

      .lg-diff-light .lg-diff-added .lg-diff-ln-new {
        color: #22863a;
        background: #cdffd8;
      }

      .lg-diff-light .lg-diff-added .lg-diff-ln-old {
        background: #e6ffed;
      }

      .lg-diff-light .lg-diff-added .lg-diff-marker {
        color: #22863a;
      }

      .lg-diff-light .lg-diff-added .lg-diff-content {
        color: #24292e;
      }

      .lg-diff-dark .lg-diff-added {
        background: #1b3a1f;
      }

      .lg-diff-dark .lg-diff-added .lg-diff-ln-new {
        color: #3fb950;
        background: #245028;
      }

      .lg-diff-dark .lg-diff-added .lg-diff-ln-old {
        background: #1b3a1f;
      }

      .lg-diff-dark .lg-diff-added .lg-diff-marker {
        color: #3fb950;
      }

      .lg-diff-dark .lg-diff-added .lg-diff-content {
        color: #e6edf3;
      }

      /* 设置工具栏 */
      .lg-diff-settings-bar {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 24px;
        border-top: 1px solid;
        flex-shrink: 0;
      }

      .lg-diff-light .lg-diff-settings-bar {
        border-color: #e1e4e8;
        background: #ffffff;
      }

      .lg-diff-dark .lg-diff-settings-bar {
        border-color: #30363d;
        background: #161b22;
      }

      .lg-diff-settings-label {
        font-size: 12px;
        font-weight: 600;
        user-select: none;
      }

      .lg-diff-light .lg-diff-settings-label { color: #586069; }
      .lg-diff-dark .lg-diff-settings-label { color: #8b949e; }

      .lg-diff-settings-btn {
        width: 28px;
        height: 28px;
        border: 1px solid;
        border-radius: 6px;
        background: transparent;
        cursor: pointer;
        font-size: 13px;
        font-weight: 700;
        display: flex;
        align-items: center;
        justify-content: center;
        transition: all 0.15s;
        padding: 0;
        line-height: 1;
      }

      .lg-diff-light .lg-diff-settings-btn {
        border-color: #d1d5da;
        color: #586069;
      }

      .lg-diff-light .lg-diff-settings-btn:hover {
        background: #f3f4f6;
        border-color: #667eea;
        color: #667eea;
      }

      .lg-diff-dark .lg-diff-settings-btn {
        border-color: #30363d;
        color: #8b949e;
      }

      .lg-diff-dark .lg-diff-settings-btn:hover {
        background: #21262d;
        border-color: #667eea;
        color: #667eea;
      }

      .lg-diff-settings-btn:active {
        transform: scale(0.92);
      }

      .lg-diff-settings-value {
        font-size: 12px;
        min-width: 36px;
        text-align: center;
        font-variant-numeric: tabular-nums;
        user-select: none;
      }

      .lg-diff-light .lg-diff-settings-value { color: #24292e; }
      .lg-diff-dark .lg-diff-settings-value { color: #e6edf3; }

      .lg-diff-settings-divider {
        color: #d1d5da;
        user-select: none;
        font-size: 12px;
      }

      .lg-diff-dark .lg-diff-settings-divider {
        color: #30363d;
      }

      /* 底部 */
      .lg-diff-footer {
        display: flex;
        justify-content: flex-end;
        gap: 12px;
        padding: 16px 24px;
        border-top: 1px solid;
      }

      .lg-diff-light .lg-diff-footer {
        border-color: #e1e4e8;
        background: #f6f8fa;
      }

      .lg-diff-dark .lg-diff-footer {
        border-color: #30363d;
        background: #0d1117;
      }

      /* 按钮 */
      .lg-diff-btn {
        padding: 8px 20px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.2s;
        border: none;
      }

      .lg-diff-btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: #ffffff;
      }

      .lg-diff-btn-primary:hover {
        opacity: 0.9;
        transform: translateY(-1px);
      }

      .lg-diff-btn-secondary {
        background: transparent;
        border: 1px solid;
      }

      .lg-diff-light .lg-diff-btn-secondary {
        border-color: #d1d5da;
        color: #586069;
      }

      .lg-diff-light .lg-diff-btn-secondary:hover {
        background: #f3f4f6;
      }

      .lg-diff-dark .lg-diff-btn-secondary {
        border-color: #30363d;
        color: #8b949e;
      }

      .lg-diff-dark .lg-diff-btn-secondary:hover {
        background: #21262d;
      }
    `);
  }

  // ======================== 初始化 ========================

  function init() {
    injectStyles();

    // 使用 MutationObserver 监听页面加载
    const observer = new MutationObserver((mutations, obs) => {
      const recordId = getRecordIdFromUrl();
      if (!recordId) return;

      // 检查页面是否已充分加载
      const hasContent = document.querySelector('pre') || document.querySelector('code') || document.querySelector('.markdown-renderer');
      if (hasContent || document.readyState === 'complete') {
        injectCompareButton();
        // 不停止观察,因为页面可能会动态更新
      }
    });

    observer.observe(document.body, {
      childList: true,
      subtree: true,
    });

    // 也在 DOMContentLoaded 时尝试注入
    if (document.readyState === 'loading') {
      document.addEventListener('DOMContentLoaded', () => {
        setTimeout(injectCompareButton, 1000);
      });
    } else {
      setTimeout(injectCompareButton, 1000);
    }

    // 监听主题切换
    const themeObserver = new MutationObserver(() => {
      // 主题切换时移除旧按钮并重新注入
      const btn = document.getElementById('lg-diff-compare-btn');
      if (btn) {
        btn.remove();
        injectCompareButton();
      }
    });

    themeObserver.observe(document.documentElement, {
      attributes: true,
      attributeFilter: ['data-theme'],
    });
  }

  // 启动
  if (document.body) {
    init();
  } else {
    document.addEventListener('DOMContentLoaded', init);
  }
})();