#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Brain Pruner: Quality-based JSONL pruning (no count cap).

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.
"""
import json
from datetime import datetime
from pathlib import Path

from pulse.core.brain_utils import (
    LESSONS_JSONL, FAILS_JSONL, PATTERNS_JSONL,
    STATE_DIR, read_jsonl_entries,
)
from pulse.brain.save_writers import rewrite_jsonl

BRAIN_JSONL_FILES = [LESSONS_JSONL, FAILS_JSONL, PATTERNS_JSONL]
# Alias used by stage_maintenance.py
BRAIN_FILES = BRAIN_JSONL_FILES
ARCHIVE_DIR = STATE_DIR / "brain_archives"

QUALITY_FLOOR = 0.1  # Archive entries with quality (salience * confidence) below this


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

    to_keep = []
    to_archive = []

    for entry in entries:
        salience = entry.get("salience", 1.0)
        confidence = entry.get("confidence", 0.5)
        quality = salience * confidence
        if quality < quality_floor:
            to_archive.append(entry)
        else:
            to_keep.append(entry)

    if not to_archive:
        return  # Nothing to prune

    # Phase 2D: Log for resurrection
    try:
        from pulse.brain.plasticity.resurrection import log_pruned
        for item in to_archive:
            fp = item.get("fingerprint", "")
            title = item.get("title", item.get("content", "")[:80])
            domain = item.get("domain", "general")
            salience = float(item.get("salience", 1.0))
            if fp and title:
                log_pruned(fp, title, domain, salience)
    except Exception as e:
        import logging
        logging.warning(f"Failed to log pruned items for resurrection: {e}")

    # SQLite-first: delete dead entries by quality floor, JSONL fallback
    try:
        from pulse.brain.save_writers.jsonl_store import _jsonl_to_table
        from pulse.core.brain_db import get_conn
        table = _jsonl_to_table(jsonl_path)
        if table:
            conn = get_conn()
            with conn:
                conn.execute(
                    f"DELETE FROM {table} WHERE salience * confidence < ?",
                    (quality_floor,),
                )
    except Exception:
        pass  # SQLite unavailable — JSONL rewrite below is the fallback

    # Rewrite JSONL with living entries only
    rewrite_jsonl(jsonl_path, to_keep)

    # Archive the dead (as JSONL)
    ARCHIVE_DIR.mkdir(parents=True, exist_ok=True)
    archive_path = ARCHIVE_DIR / f"archived_{jsonl_path.stem}.jsonl"
    with open(archive_path, "a", encoding="utf-8") as f:
        for entry in to_archive:
            entry["_archived_at"] = datetime.now().isoformat()
            f.write(json.dumps(entry, ensure_ascii=False) + "\n")
    print(f"[PRUNE] Archived {len(to_archive)} dead entries from {jsonl_path.name} (quality < {quality_floor})")


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

# Alias used by stage_maintenance.py and other callers
prune_file = prune_jsonl

if __name__ == "__main__":
    run()
