"""
Phase 3D: Epistemic Qualifiers

Attach `[UNCERTAIN]`, `[STALE 30d]`, `[CONTESTED]` prefixes to search results.
Agents see honest uncertainty.
"""
import re


def _strip_existing_prefixes(text: str) -> str:
    """Remove all existing epistemic [TAG] prefixes from text."""
    while re.match(r'^\[[\w\s\d]+\]\s*', text):
        text = re.sub(r'^\[[\w\s\d]+\]\s*', '', text)
    return text

def apply_epistemic_qualifiers(item: dict) -> dict:
    """Evaluates an item and prepends epistemic tags to its title or text."""
    prefixes = []

    # Check source_type for CONFIRMED — read from item dict (real column via _row_to_hit)
    source_type = item.get("source_type", "")

    # 0. CONFIRMED — positive ground truth signal; suppress [UNCERTAIN], set flag
    if source_type == "CONFIRMED" or item.get("_confirmed"):
        item["_confirmed"] = True
        prefixes.append("[CONFIRMED]")
        # Skip uncertainty checks — this item has been validated in production
        if prefixes:
            prefix_str = " ".join(prefixes) + " "
            for key in ("title", "content", "text"):
                if key in item and item[key]:
                    item[key] = _strip_existing_prefixes(item[key])
                    item[key] = prefix_str + item[key]
        return item

    # 1. Contested
    if item.get("validity") == "contested" or item.get("_contradiction_flag"):
        prefixes.append("[CONTESTED]")

    # 2. Uncertain
    conf = item.get("confidence", 0.5)
    # Use Wilson lower bound only when evidence_count >= 2; at n=1 Wilson is
    # meaningless (always collapses near 0) so use raw confidence instead.
    ec = item.get("evidence_count", 1) or 1
    if ec >= 2:
        effective_conf = item.get("_wilson_lower", conf)
    else:
        effective_conf = conf  # Wilson meaningless at n=1
    # Threshold 0.25 (was 0.4): young brain has most items at evidence_count=1
    # which clusters Wilson lower bounds near 0.2-0.35. At 0.4 threshold,
    # 85%+ of items got flagged UNCERTAIN, degrading trust in valid knowledge.
    if effective_conf < 0.25:
        # CONVERSATIONAL with low confidence — keep [UNCERTAIN]
        prefixes.append("[UNCERTAIN]")

    # 3. Low-confidence domain (from metamemory)
    if item.get("_low_confidence_domain"):
        level = item.get("_domain_competence", "unknown")
        if level in ("blind_spot", "novice"):
            prefixes.append("[LOW DOMAIN CONF]")

    # 4. Stale
    # If the item hasn't been accessed or reinforced recently
    from pulse.core.temporal import _days_since
    anchor = item.get("last_accessed") or item.get("last_reinforced") or item.get("timestamp")
    if anchor:
        age_days = _days_since(anchor)
        if age_days > 30:
            prefixes.append(f"[STALE {int(age_days)}d]")

    if prefixes:
        prefix_str = " ".join(prefixes) + " "
        # Strip existing prefixes before applying new ones to prevent accumulation
        for key in ("title", "content", "text"):
            if key in item and item[key]:
                item[key] = _strip_existing_prefixes(item[key])
                item[key] = prefix_str + item[key]

    return item