why code below for this page https://f95zone.to/threads/young-again-s2-ch-9-public-zargon_games.56677/ it add compressed link to https://f95zone.to/threads/young-again-s2-ch-9-public-zargon_games.56677/post-17532617 (post contains "anyone has season one compressed") instead of https://f95zone.to/threads/young-again-s2-ch-9-public-zargon_games.56677/post-17522955 (post contains proper text "Young Again [S2 Ch. 9 Public] [Zargon_games] COMPRESSED: Win/Linux: AKIRABOX - MEGA - PIXELDRAIN - WORKUPLOAD Mac: AKIRABOX - MEGA - PIXELDRAIN - WORKUPLOAD")?
// ==UserScript==
// @name         F95Zone "compressed version" Link Above Thumbnails (Exclude Quoted Posts)
// @namespace    http://tampermonkey.net/
// @version      1.40
// @description  Insert "compressed version" link; excludes quote posts, picks highest version/chapter, oldest non-quote post
// @match        https://f95zone.to/threads/*
// @grant        GM_xmlhttpRequest
// @connect      f95zone.to
// ==/UserScript==

(function() {
    'use strict';

    function extractVersion(titleText) {
        const versionRegex = /v(?:ersion)?[\s\-_]?(\d+(?:\.\d+){0,2})/i;
        const cleaned = titleText.replace(/[\[\]\(\)]/g, ' ');
        const match = cleaned.match(versionRegex);
        return (match && match[1]) ? 'v' + match[1] : null;
    }

    function createCompressedVersionLink(label, href) {
        const link = document.createElement('a');
        link.href = href;
        link.textContent = label;
        link.target = '_blank';
        link.rel = "noopener noreferrer";
        link.style.cssText = `
            display: inline-block;
            margin: 10px 0 12px 0;
            padding: 8px 14px;
            background-color: #ba4545;
            color: white;
            font-weight: bold;
            font-size: 14px;
            text-decoration: none;
            border-radius: 4px;
            cursor: pointer;
        `;
        link.title = 'Go to compressed version post';
        return link;
    }

    function insertLinkAboveDownloadDiv(firstPost, element) {
        const candidates = firstPost.querySelectorAll('div[style*="text-align: center"]');
        for (const div of candidates) {
            if (div.textContent.trim().toUpperCase().includes('DOWNLOAD')) {
                div.parentNode.insertBefore(element, div);
                return true;
            }
        }
        firstPost.insertBefore(element, firstPost.firstChild);
        return false;
    }

    function floatCompare(a, b) {
        if (a > b) return 1;
        else if (a < b) return -1;
        else return 0;
    }

    function looksLikeQuote(snippet) {
        if (!snippet) return false;
        const s = snippet.trim().toLowerCase();
        // Common pattern for quotes in F95Zone search snippets
        return s.includes('said:') || s.startsWith('quote') || s.startsWith('spoiler');
    }

    function extractCleanVersion(text) {
        if (!text) return null;
        const m = text.match(/\bv(\d+(?:\.\d+){0,2})\b/i);
        return m ? 'v' + m[1] : null;
    }

    function parseVersionString(vstr) {
        if (!vstr) return 0;
        const m = vstr.match(/v(\d+(?:\.\d+){0,2})/i);
        return m ? parseFloat(m[1]) : 0;
    }

    function extractChapterKey(text) {
        if (!text) return 0;
        const m = text.match(/s(\d+).*?ch(?:apter)?\.? ?(\d+)/i);
        if (m) {
            const season = parseInt(m[1], 10) || 0;
            const chapter = parseInt(m[2], 10) || 0;
            return season + chapter / 100;
        }
        const m2 = text.match(/\b(?:ch|ep|chapter|episode)\.? ?(\d+)/i);
        if (m2) {
            const chapter = parseInt(m2[1], 10) || 0;
            return chapter / 100;
        }
        return 0;
    }

    function findOldestCompressedPost(html) {
        const doc = new DOMParser().parseFromString(html, 'text/html');
        const items = [...doc.querySelectorAll('li.js-inlineModContainer')];
        console.log("DEBUG: Found search result items =", items.length);

        // Regex for release hosts and sizes – real compressed release indicators
        const releaseIndicatorRegex = /(mega|mediafire|pixeldrain|krakenfiles|vikingfile|patch|download|win|linux|mac|full|public|release|gb|mb|uploaded|rar|7z)/i;

        const candidates = items.map((li, idx) => {
            const contentRow = li.querySelector('.contentRow-main');
            if (!contentRow) return null;

            const postLinkElem = contentRow.querySelector('h3.contentRow-title a[href]');
            if (!postLinkElem) return null;
            const postUrl = postLinkElem.href;

            const snippetElem = contentRow.querySelector('.contentRow-snippet');
            const titleElem = contentRow.querySelector('h3.contentRow-title');
            if (!snippetElem && !titleElem) return null;

            const snippetTextRaw = snippetElem ? snippetElem.textContent.trim() : '';
            const snippetTextLower = snippetTextRaw.toLowerCase();
            const titleText = titleElem ? titleElem.textContent.toLowerCase() : '';
            const combinedText = snippetTextLower + ' ' + titleText;

            // Require "compressed" keyword
            if (!combinedText.includes('compressed')) {
                console.log(`DEBUG [${idx}] Skipped: missing "compressed" keyword`);
                return null;
            }

            // Require at least one release host/size keyword for actual compressed releases
            if (!releaseIndicatorRegex.test(combinedText)) {
                console.log(`DEBUG [${idx}] Skipped: missing release host or size keywords`);
                return null;
            }

            // Exclude quote posts based on snippet content
            if (looksLikeQuote(snippetTextRaw)) {
                console.log(`DEBUG [${idx}] Skipped: snippet indicates quoted post`);
                return null;
            }

            const hasVersion = /\bv\d+(\.\d+)*\b/.test(combinedText);
            const hasChapter = /\b(ch|ep|chapter|episode|season|s)\b[\s\-\.:#]*\d+/i.test(combinedText);
            const releaseWords = ['win', 'linux', 'mac', 'patch', 'public', 'full', 'release'];
            const hasReleaseWords = releaseWords.some(w => combinedText.includes(w));
            if (!(hasVersion || hasChapter || hasReleaseWords)) {
                console.log(`DEBUG [${idx}] Skipped: missing version/chapter/release keywords`);
                return null;
            }

            const timeElem = li.querySelector('time.u-dt');
            if (!timeElem) {
                console.log(`DEBUG [${idx}] Skipped: no time element`);
                return null;
            }
            const datetime = timeElem.getAttribute('datetime');
            if (!datetime) {
                console.log(`DEBUG [${idx}] Skipped: no datetime attribute`);
                return null;
            }
            const dateObj = new Date(datetime);
            if (isNaN(dateObj.getTime())) {
                console.log(`DEBUG [${idx}] Skipped: invalid date`);
                return null;
            }

            const isQuote = false; // already filtered quoted posts

            const extractedVersion = extractCleanVersion(combinedText);
            const parsedVersion = parseVersionString(extractedVersion);

            const chapterKey = parsedVersion ? parsedVersion : extractChapterKey(combinedText);

            console.log(`DEBUG [${idx}] Candidate: URL=${postUrl} ver=${extractedVersion} verParsed=${parsedVersion} chapterKey=${chapterKey.toFixed(2)} date=${dateObj.toISOString()} quote=${isQuote}`);

            return { url: postUrl, date: dateObj, isQuote, extractedVersion, parsedVersion, chapterKey };
        }).filter(Boolean);

        if (!candidates.length) {
            console.log("DEBUG: No candidates found.");
            return null;
        }

        let maxKey = candidates[0].chapterKey;
        candidates.forEach(c => {
            if (floatCompare(c.chapterKey, maxKey) > 0) maxKey = c.chapterKey;
        });

        console.log(`DEBUG: Highest version/chapter key: ${maxKey.toFixed(2)}`);

        const maxKeyCandidates = candidates.filter(c => floatCompare(c.chapterKey, maxKey) === 0);

        console.log(`DEBUG: Candidates with max key count: ${maxKeyCandidates.length}`);
        maxKeyCandidates.forEach((c,i) => {
            console.log(`DEBUG [${i}]: URL=${c.url}, Date=${c.date.toISOString()}, Quote=${c.isQuote}`);
        });

        // Oldest non-quote post prioritized
        const nonQuoteCandidates = maxKeyCandidates.filter(c => !c.isQuote);
        if (nonQuoteCandidates.length) {
            nonQuoteCandidates.sort((a,b) => a.date - b.date);
            console.log(`DEBUG: Returning oldest non-quote URL=${nonQuoteCandidates[0].url}`);
            return nonQuoteCandidates[0].url;
        }

        // Fallback newest quote post (should not happen here)
        maxKeyCandidates.sort((a,b) => b.date - a.date);
        console.log(`DEBUG: Returning newest quote URL=${maxKeyCandidates[0].url}`);
        return maxKeyCandidates[0].url;
    }

    window.floatCompare = function(a, b) {
        if (a > b) return 1;
        if (a < b) return -1;
        return 0;
    };

    function postSearchPage(url, paramsObj) {
        return new Promise((resolve, reject) => {
            const params = new URLSearchParams();
            for (const key in paramsObj) {
                if (Object.hasOwnProperty.call(paramsObj, key)) {
                    params.append(key, paramsObj[key]);
                }
            }

            GM_xmlhttpRequest({
                method: "POST",
                url: url,
                headers: {
                    "User-Agent": navigator.userAgent,
                    "Accept": "text/html,text/plain",
                    "Content-Type": "application/x-www-form-urlencoded",
                    "Referer": window.location.href
                },
                data: params.toString(),
                onload: r => {
                    if (r.status >= 200 && r.status < 300) {
                        console.log("DEBUG: POST search HTML response received.");
                        resolve(r.responseText);
                    } else {
                        reject(new Error(`HTTP ${r.status}`));
                    }
                },
                onerror: reject,
                anonymous: false
            });
        });
    }

    window.addEventListener('load', () => {
        try {
            const titleElem = document.querySelector('h1.p-title-value');
            if (!titleElem) return;

            const version = extractVersion(titleElem.textContent || '');
            let searchQuery = 'compressed';
            if (version) {
                searchQuery += ' ' + version;
            }

            const firstPost = document.querySelector('.message-threadStarterPost.message--post.js-post');
            if (!firstPost) return;

            if (/compressed/i.test(firstPost.textContent)) {
                return; // First post already mentions compressed, skip
            }

            const threadIdMatch = window.location.pathname.match(/[.-]([0-9]+)(?:\/|$)/);
            if (!threadIdMatch) {
                console.warn('Thread ID not found in URL');
                return;
            }
            const threadId = threadIdMatch[1];

            const xfTokenInput = document.querySelector('input[name="_xfToken"]');
            if (!xfTokenInput) {
                console.warn('CSRF token input _xfToken not found!');
                return;
            }
            const xfToken = xfTokenInput.value;

            const postUrl = `${window.location.origin}/search/search`;

            const constraints = JSON.stringify({
                search_type: "post",
                c: { thread: Number(threadId) }
            });

            const paramsObj = {
                q: searchQuery,
                _xfToken: xfToken,
                constraints: constraints,
                o: 'date',
            };

            postSearchPage(postUrl, paramsObj)
                .then(html => {
                    const foundUrl = findOldestCompressedPost(html);

                    if (!foundUrl) {
                        const noLinkSpan = document.createElement('span');
                        noLinkSpan.textContent = 'No compressed version link found';
                        noLinkSpan.style.color = '#ba4545';
                        noLinkSpan.style.display = 'block';
                        noLinkSpan.style.margin = '10px 0 12px 0';
                        insertLinkAboveDownloadDiv(firstPost, noLinkSpan);
                        return;
                    }

                    const link = createCompressedVersionLink('compressed version', foundUrl);
                    insertLinkAboveDownloadDiv(firstPost, link);
                })
                .catch(err => {
                    console.error('POST search fetch failed:', err);
                });
        } catch (e) {
            console.error(e);
        }
    });
})();