"""Post-processing for Markdown that will be fed to a model."""

from __future__ import annotations

import re
from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit

TRACKING_PREFIXES = ("utm_", "mc_", "_hs")
TRACKING_KEYS = {"fbclid", "gclid", "dclid", "msclkid", "yclid", "igshid", "ref_src", "mkt_tok"}


def strip_tracking(url: str) -> str:
    """Remove common tracking parameters and the fragment-free tail stays intact."""
    parts = urlsplit(url)
    if not parts.query:
        return url
    kept = [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True)
            if k.lower() not in TRACKING_KEYS and not k.lower().startswith(TRACKING_PREFIXES)]
    return urlunsplit((parts.scheme, parts.netloc, parts.path, urlencode(kept), parts.fragment))


_BLANKS = re.compile(r"\n{3,}")
_TRAILING = re.compile(r"[ \t]+\n")


def clean_markdown(md: str, drop_repeated_lines: bool = True, min_repeat: int = 3) -> str:
    """Collapse blank lines, trim trailing spaces and drop short lines repeated many times
    (leftover boilerplate such as "Share", "Read more", "Advertisement")."""
    md = _TRAILING.sub("\n", md)
    lines = md.split("\n")
    if drop_repeated_lines:
        counts = {}
        for ln in lines:
            key = ln.strip()
            if key and len(key) < 40 and not key.startswith(("#", "|", "-", "*", "```")):
                counts[key] = counts.get(key, 0) + 1
        noisy = {k for k, c in counts.items() if c >= min_repeat}
        lines = [ln for ln in lines if ln.strip() not in noisy]
    out = "\n".join(lines)
    return _BLANKS.sub("\n\n", out).strip() + "\n"
