
import re
from pathlib import Path
from datetime import datetime

SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent.parent

import sys
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

BRAIN_FILES = [
    ROOT_DIR / "Hippocampus" / "Lessons" / "auto_lessons.md",
    ROOT_DIR / "Hippocampus" / "Failures" / "auto_fails.md",
    ROOT_DIR / "Hippocampus" / "Patterns" / "auto_patterns.md",
]
ARCHIVE_DIR = ROOT_DIR / "Hippocampus" / "archive"

# NO COUNT CAP. Brain grows forever like a real brain.
# Only quality-based pruning: entries with confidence decayed below threshold
# by LTD decay (stage_ltd_decay) get archived. Everything else stays.
# Search ranking (relevance + recency + salience) handles what surfaces.
QUALITY_FLOOR = 0.1  # Archive entries with quality (salience * confidence) below this


def _extract_quality(entry_text: str) -> float:
    """Extract quality score from entry metadata (salience * confidence).

    Falls back to 0.5 if metadata is missing (old entries without salience).
    """
    salience = 1.0
    confidence = 0.5
    sal_match = re.search(r'\*\*Salience:\*\*\s*([\d.]+)', entry_text)
    if sal_match:
        try:
            salience = float(sal_match.group(1))
        except ValueError:
            pass
    conf_match = re.search(r'\*\*Confidence:\*\*\s*([\d.]+)', entry_text)
    if conf_match:
        try:
            confidence = float(conf_match.group(1))
        except ValueError:
            pass
    return salience * confidence


def prune_file(path: Path, quality_floor: float = QUALITY_FLOOR):
    """Prune only dead entries (quality below floor). No count cap."""
    if not path.exists():
        return

    content = path.read_text(encoding="utf-8")
    sections = re.split(r'\n(?=## )', content)
    if len(sections) <= 1:
        return

    header = sections[0]
    entries = sections[1:]

    to_keep = []
    to_archive = []

    for entry in entries:
        quality = _extract_quality(entry)
        if quality < quality_floor:
            to_archive.append(entry)
        else:
            to_keep.append(entry)

    if not to_archive:
        return  # Nothing to prune

    # Rewrite file with living entries only
    if to_keep:
        kept_content = header + "\n" + "\n".join(to_keep)
    else:
        kept_content = header
    path.write_text(kept_content, encoding="utf-8")

    # Archive the dead
    ARCHIVE_DIR.mkdir(parents=True, exist_ok=True)
    archive_path = ARCHIVE_DIR / f"archived_{path.name}"
    timestamp = datetime.now().isoformat()
    with open(archive_path, "a", encoding="utf-8") as f:
        f.write(f"\n\n# Archived from {path.name} on {timestamp}\n")
        f.write("".join(to_archive))
    print(f"[PRUNE] Archived {len(to_archive)} dead entries from {path.name} (quality < {quality_floor})")


def run():
    print(f"[PRUNE] Starting brain pruning at {datetime.now().isoformat()}")
    for path in BRAIN_FILES:
        try:
            prune_file(path)
        except Exception as e:
            print(f"[PRUNE] Error pruning {path.name}: {e}")
    print("[PRUNE] Pruning complete.")

if __name__ == "__main__":
    run()
