"""
Phase 3D: Epistemic Qualifiers

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


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 = []
    
    # 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 if available, else raw confidence
    effective_conf = item.get("_wilson_lower", conf)
    if effective_conf < 0.4:
        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(f"[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