#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Brain self-assessment summary — Item 175.

  - Item 175: Brain self-assessment summary (Monitoring)

Combine all metamemory metrics into one brain health report:
entropy, utilization, calibration, growth rate, decay rate,
integration index. Single function returns complete assessment.
"""
import logging
from datetime import datetime, timezone
from typing import Dict, Any

log = logging.getLogger("pulse.brain.brain_self_assessment")


def get_brain_health_report() -> Dict[str, Any]:
    """Return a complete brain health assessment combining all P36-P40 metrics.

    Aggregates:
        - Brain entropy (from metamemory_p34.compute_brain_entropy)
        - Brain utilization (from metamemory.get_brain_utilization)
        - Confidence distribution (from metamemory_p36.get_confidence_histogram)
        - Growth rate (from brain_growth_monitor.get_growth_rate)
        - Decay rate (from metamemory_p34.get_decay_rate_24h)
        - Integration index (from memory_integration_index.get_integration_index)
        - Brain age (from metamemory_p36.get_brain_age_metric)
        - Cognitive load (from metamemory_p36.get_cognitive_load_status)
        - Knowledge gaps (from knowledge_gap_map.get_knowledge_gaps)
        - Rehearsal candidates (from metamemory_p36.get_rehearsal_candidates)

    Returns a flat summary dict with all key metrics and a list of warnings.
    Fails open (returns partial data) on any error — each sub-metric is
    independently fetched and failures are silently swallowed.
    """
    report: Dict[str, Any] = {
        "timestamp": datetime.now(timezone.utc).isoformat(),
        "warnings": [],
        # Sub-sections populated below
        "entropy": None,
        "utilization": None,
        "confidence_distribution": None,
        "growth_rate": None,
        "decay_rate": None,
        "integration_index": None,
        "brain_age_days": None,
        "cognitive_load": None,
        "knowledge_gap_count": None,
        "rehearsal_needed_count": None,
        "overall_health": "unknown",
    }

    # --- Entropy ---
    try:
        from pulse.brain.metacognition.metamemory_p34 import compute_brain_entropy
        entropy_data = compute_brain_entropy()
        report["entropy"] = entropy_data.get("entropy")
    except Exception:
        pass

    # --- Utilization ---
    try:
        from pulse.brain.metacognition.metamemory import get_brain_utilization
        util = get_brain_utilization()
        report["utilization"] = util.get("utilization_rate")
    except Exception:
        pass

    # --- Confidence distribution ---
    try:
        from pulse.brain.metacognition.metamemory_p36 import get_confidence_histogram
        hist = get_confidence_histogram()
        report["confidence_distribution"] = {
            "uncertain_pct": hist.get("uncertain_pct"),
            "total": hist.get("total"),
        }
        if hist.get("alert"):
            report["warnings"].append(hist["alert"])
    except Exception:
        pass

    # --- Growth rate ---
    try:
        from pulse.brain.monitoring.brain_growth_monitor import get_growth_rate
        growth = get_growth_rate()
        report["growth_rate"] = growth.get("avg_per_day")
        if growth.get("warning"):
            report["warnings"].append(growth["warning"])
    except Exception:
        pass

    # --- Decay rate ---
    try:
        from pulse.brain.metacognition.metamemory_p34 import get_decay_rate_24h
        decay = get_decay_rate_24h()
        report["decay_rate"] = decay.get("decay_rate_pct")
        if decay.get("warning"):
            report["warnings"].append(
                f"!! DECAY WARNING: {decay['decay_rate_pct']}% of items decayed in 24h"
            )
    except Exception:
        pass

    # --- Integration index ---
    try:
        from pulse.brain.monitoring.memory_integration_index import get_integration_index
        integ = get_integration_index()
        report["integration_index"] = integ.get("integration_index")
        if integ.get("warning"):
            report["warnings"].append(integ["warning"])
    except Exception:
        pass

    # --- Brain age ---
    try:
        from pulse.brain.metacognition.metamemory_p36 import get_brain_age_metric
        age_data = get_brain_age_metric()
        report["brain_age_days"] = age_data.get("age_days")
    except Exception:
        pass

    # --- Cognitive load ---
    try:
        from pulse.brain.metacognition.metamemory_p36 import get_cognitive_load_status
        load = get_cognitive_load_status()
        report["cognitive_load"] = load.get("active_agents")
        if load.get("recommendation"):
            report["warnings"].append(load["recommendation"])
    except Exception:
        pass

    # --- Knowledge gaps ---
    try:
        from pulse.brain.metacognition.knowledge_gap_map import get_knowledge_gaps
        gaps = get_knowledge_gaps()
        report["knowledge_gap_count"] = gaps.get("gap_count")
        if gaps.get("warning"):
            report["warnings"].append(gaps["warning"])
    except Exception:
        pass

    # --- Rehearsal candidates ---
    try:
        from pulse.brain.metacognition.metamemory_p36 import get_rehearsal_candidates
        rehearsal = get_rehearsal_candidates()
        report["rehearsal_needed_count"] = rehearsal.get("total")
        if rehearsal.get("warning"):
            report["warnings"].append(rehearsal["warning"])
    except Exception:
        pass

    # --- Learning velocity (Item 173) ---
    try:
        from pulse.brain.monitoring.learning_velocity import get_learning_velocity
        report["learning_velocity"] = get_learning_velocity()
    except Exception:
        pass

    # --- Consolidation debt ---
    try:
        from pulse.brain.metacognition.metamemory_tracking import get_consolidation_debt
        report["consolidation_debt"] = get_consolidation_debt()
    except Exception:
        pass

    # --- Overall health assessment ---
    try:
        n_warnings = len(report["warnings"])
        if n_warnings == 0:
            report["overall_health"] = "healthy"
        elif n_warnings <= 2:
            report["overall_health"] = "caution"
        else:
            report["overall_health"] = "degraded"
    except Exception:
        pass

    return report
