#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Stages 6/8/10/11/12: Pruning, truth verification, metamemory, homeostasis, deep consolidation."""
from collections import defaultdict
from datetime import datetime, timezone, timedelta

from pulse.core.brain_utils import (
    LESSONS_DIR, PATTERNS_DIR, FAILS_DIR,
    LESSONS_JSONL, FAILS_JSONL, PATTERNS_JSONL,
    read_jsonl_entries, now_iso as _now_iso,
)
from .stage_io import _MD_TO_JSONL

def stage_hierarchical_prune(verbose=False):
    """Stage 6: Miller's Law — max 5 items per section, 200 entries per file.
    P48 Fix 2E: Reads SQLite directly (10K+ entries) instead of JSONL (381 entries).
    """
    from pulse.core.brain_utils import load_config
    from pulse.admin.brain_ops.pulse_prune import prune_file, BRAIN_FILES
    from pulse.brain.save_writers import rewrite_jsonl
    config = load_config()
    max_chunk = config.get("validation", {}).get("max_chunk_size", 5)

    for bf in BRAIN_FILES:
        try:
            prune_file(bf)
        except Exception as e:
            if verbose:
                print(f"  [PRUNE-L1] Error pruning {bf.name}: {e}")

    trimmed_total = 0
    domain_cap = max_chunk * 2000  # 10000 entries per domain cap
    _tables = ["lessons", "failures", "patterns"]

    try:
        from pulse.core.brain_db import get_conn
        conn = get_conn()
        for table in _tables:
            try:
                rows = conn.execute(
                    f"SELECT id, content, domain, confidence, salience, fingerprint FROM {table} WHERE validity != 'archived' ORDER BY domain"
                ).fetchall()
            except Exception:
                continue
            if not rows:
                continue
            by_domain = defaultdict(list)
            for row in rows:
                r = dict(row)
                r.setdefault("domain", "general")
                by_domain[r["domain"]].append(r)
            fps_to_delete = []
            for domain, items in by_domain.items():
                items.sort(key=lambda x: (x.get("salience") or 1.0) * (x.get("confidence") or 0.5), reverse=True)
                if len(items) > domain_cap:
                    over_cap = items[domain_cap:]
                    fps_to_delete.extend(r["fingerprint"] for r in over_cap if r.get("fingerprint"))
                    trimmed_total += len(over_cap)
            if fps_to_delete:
                with conn:
                    placeholders = ",".join("?" * len(fps_to_delete))
                    try:
                        conn.execute(
                            f"DELETE FROM knowledge_fts WHERE item_id IN "
                            f"(SELECT id FROM {table} WHERE fingerprint IN ({placeholders}))",
                            fps_to_delete,
                        )
                    except Exception:
                        pass
                    conn.execute(
                        f"DELETE FROM {table} WHERE fingerprint IN ({placeholders})",
                        fps_to_delete,
                    )
    except Exception as e:
        if verbose:
            print(f"  [PRUNE] SQLite prune error: {e}")

    if verbose:
        print(f"  [PRUNE] Hierarchical: {trimmed_total} over-limit items trimmed")
    return {"status": "ok", "trimmed": trimmed_total}

def stage_truth_verification(verbose=False):
    """Stage 8: Dimension A — scan for contradictions and apply penalties."""
    from pulse.admin.audit.truth_verifier import scan_contradictions, apply_penalties
    scan = scan_contradictions(verbose=verbose)
    penalized = apply_penalties(verbose=verbose)
    return {"status": "ok", "new_contradictions": scan["new"],
            "pending": scan["pending"], "penalized": penalized}

def stage_10_metamemory(verbose=False):
    """Stage 10: Compute domain-level confidence map for self-modeling."""
    try:
        from pulse.brain.metacognition.metamemory import compute_metamemory
        metamap = compute_metamemory()
        gaps = sum(1 for d in metamap.values() if d.get("gap_flag"))
        if verbose:
            print(f"  [METAMEMORY] {len(metamap)} domains, {gaps} flagged as gaps.")
        return {"status": "ok", "domains": len(metamap), "gaps": gaps}
    except ImportError:
        if verbose:
            print("  [METAMEMORY] pulse.brain.metacognition.metamemory not found")
        return {"status": "skipped"}
    except Exception as e:
        if verbose:
            print(f"  [METAMEMORY] Error: {e}")
        return {"error": str(e)}

# ---------------------------------------------------------------------------
# Re-exports from stage_maintenance_homeostasis (preserves public API)
# ---------------------------------------------------------------------------
from .stage_maintenance_homeostasis import (  # noqa: F401
    stage_synaptic_homeostasis, stage_deep_consolidation, stage_recency_bonus,
)

# Item 116: Memory consolidation priority queue — re-exported from dedicated module
try:
    from pulse.daemons.consolidation.stages.stage_priority_queue import (
        stage_consolidation_priority_queue,
        build_consolidation_priority_queue,
    )
except Exception:
    def stage_consolidation_priority_queue(items=None, verbose=False):
        return {"status": "skipped", "total": 0, "ordered_items": []}
    def build_consolidation_priority_queue(items):
        return list(items) if items else []
