#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Neuroscience helpers: decay, weighted counts, cross-domain detection, density.

Split from brain_analysis.py for Law 7 compliance.
"""
from pathlib import Path


def compute_weighted_count(items: list, config: dict) -> float:
    """Weighted count: FAIL items weighted higher (error-driven learning #33-34)."""
    fail_weight = config.get("synthesis", {}).get("fail_weight", 2.5)
    total = 0.0
    for item in items:
        if item.get("type") == "fail":
            total += fail_weight
        else:
            total += 1.0
    return total


def compute_confidence_decay(confidence: float, days_old: int,
                             decay_rate: float = 0.005,
                             knowledge_type: str = "lesson") -> float:
    """Apply confidence decay with type-aware half-life (Dimension D).

    Uses exponential half-life model instead of flat linear decay.
    Falls back to flat rate if temporal module unavailable.
    """
    try:
        from pulse.core.temporal import temporal_confidence
        return temporal_confidence(confidence, float(days_old),
                                   knowledge_type=knowledge_type)
    except ImportError:
        decayed = confidence * ((1.0 - decay_rate) ** days_old)
        return max(0.0, round(decayed, 4))


def detect_cross_domain_patterns(evidence_dir: Path) -> list:
    """Find patterns appearing in 2+ domains (transfer detection #16, #29)."""
    from pulse.core.brain_io import load_json
    if not evidence_dir.exists():
        return []
    pattern_domains = {}
    for ef in sorted(evidence_dir.glob("*.json")):
        from pulse.core.brain_analysis import extract_domain
        domain = extract_domain(ef.name)
        items = load_json(ef)
        if isinstance(items, list):
            for item in items:
                p = item.get("pattern", "")
                if p:
                    pattern_domains.setdefault(p, set()).add(domain)
    return [{"pattern": p, "domains": sorted(d), "count": len(d),
             "universal": len(d) >= 3}
                         for p, d in pattern_domains.items() if len(d) >= 2]


def get_brain_density() -> dict:
    """Calculates synaptic density and integrity across all evidence chambers."""
    from pulse.core.brain_io import load_json
    from pulse.core.brain_utils import EVIDENCE_DIR, PRIVATE_DIR
    stats = {"total_items": 0, "signed_items": 0, "domains": 0}
    chambers = [EVIDENCE_DIR, PRIVATE_DIR]

    for chamber in chambers:
        if not chamber.exists(): continue
        for ef in chamber.rglob("*.json"):
            items = load_json(ef)
            if not isinstance(items, list): continue
            stats["domains"] += 1
            for item in items:
                stats["total_items"] += 1
                if "_signature" in item:
                    stats["signed_items"] += 1

    stats["integrity_ratio"] = stats["signed_items"] / stats["total_items"] if stats["total_items"] > 0 else 1.0
    return stats
