#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Brain growth rate monitoring — Item 161.

  - Item 161: Brain growth rate monitoring (Monitoring)

Track items added per day over the last 7 days.
Alert if growth rate drops to 0 (brain has stopped learning).
"""
import logging
from datetime import datetime, timezone, timedelta
from typing import Dict, Any, List

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

_WINDOW_DAYS = 7


def get_growth_rate() -> Dict[str, Any]:
    """Compute items added per day over the last 7 days.

    Returns:
        {
            daily_counts: {date_str: count},
            total_7d: int,
            avg_per_day: float,
            zero_growth_days: int,
            warning: str or None,
        }
    Fails open (returns zeros) on any error.
    """
    result: Dict[str, Any] = {
        "daily_counts": {},
        "total_7d": 0,
        "avg_per_day": 0.0,
        "zero_growth_days": 0,
        "warning": None,
    }
    try:
        from pulse.core.brain_db import get_conn
        conn = get_conn()
        now = datetime.now(timezone.utc)
        daily: Dict[str, int] = {}

        for i in range(_WINDOW_DAYS):
            day = (now - timedelta(days=i)).strftime("%Y-%m-%d")
            daily[day] = 0

        for tbl in ("lessons", "failures", "patterns", "facts"):
            cutoff = (now - timedelta(days=_WINDOW_DAYS)).isoformat()
            try:
                rows = conn.execute(
                    f"SELECT timestamp FROM {tbl} "
                    f"WHERE timestamp >= ? AND validity = 'valid'",
                    (cutoff,)
                ).fetchall()
                for row in rows:
                    try:
                        ts_str = str(row[0] or "")
                        if ts_str:
                            day = ts_str[:10]  # YYYY-MM-DD
                            if day in daily:
                                daily[day] += 1
                    except Exception:
                        pass
            except Exception:
                pass

        total = sum(daily.values())
        zero_days = sum(1 for v in daily.values() if v == 0)
        avg_per_day = round(total / _WINDOW_DAYS, 2)

        warning = None
        if zero_days >= _WINDOW_DAYS:
            warning = (
                "!! BRAIN GROWTH STALLED: Zero new items added in the last 7 days. "
                "Pipeline may be broken."
            )
        elif zero_days >= _WINDOW_DAYS // 2:
            warning = (
                f"!! LOW BRAIN GROWTH: {zero_days}/{_WINDOW_DAYS} days with zero additions "
                "in the last week."
            )

        result.update({
            "daily_counts": daily,
            "total_7d": total,
            "avg_per_day": avg_per_day,
            "zero_growth_days": zero_days,
            "warning": warning,
        })

    except Exception as exc:
        log.debug("get_growth_rate failed: %s", exc)

    return result
