#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Learning velocity per domain — Item 173.

  - Item 173: Learning velocity per domain (Learning)

Track how fast confidence grows in each domain.
Fast learners = good extraction. Slow learners = need more evidence.
"""
import logging
from datetime import datetime, timezone, timedelta
from typing import Dict, Any, List

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

_WINDOW_DAYS = 30   # compare confidence over last 30 days


def get_learning_velocity() -> Dict[str, Any]:
    """Compute confidence growth rate per domain over the last 30 days.

    Velocity = (current_avg_confidence - month_ago_avg_confidence) / 30 days.

    Returns:
        {
            domains: {domain: {current_conf, past_conf, velocity, trend}},
            fastest_learner: str or None,
            slowest_learner: str or None,
        }
    Fails open (returns empty) on any error.
    """
    result: Dict[str, Any] = {
        "domains": {},
        "fastest_learner": None,
        "slowest_learner": None,
    }
    try:
        from pulse.core.brain_db import get_conn
        conn = get_conn()
        now = datetime.now(timezone.utc)
        cutoff = (now - timedelta(days=_WINDOW_DAYS)).isoformat()

        # Current average confidence per domain (all valid items)
        current: Dict[str, List[float]] = {}
        # Past average: items older than cutoff
        past: Dict[str, List[float]] = {}

        for tbl in ("lessons", "failures", "patterns", "facts"):
            try:
                # Current
                rows = conn.execute(
                    f"SELECT domain, confidence FROM {tbl} WHERE validity = 'valid'"
                ).fetchall()
                for row in rows:
                    d = str(row[0] or "general")
                    try:
                        current.setdefault(d, []).append(float(row[1] or 0.0))
                    except Exception:
                        pass

                # Past (items created before cutoff)
                rows_past = conn.execute(
                    f"SELECT domain, confidence FROM {tbl} "
                    f"WHERE validity = 'valid' AND timestamp < ?",
                    (cutoff,)
                ).fetchall()
                for row in rows_past:
                    d = str(row[0] or "general")
                    try:
                        past.setdefault(d, []).append(float(row[1] or 0.0))
                    except Exception:
                        pass
            except Exception:
                pass

        velocities: Dict[str, float] = {}
        domains_result: Dict[str, Dict[str, Any]] = {}

        for domain, curr_confs in current.items():
            if not curr_confs:
                continue
            curr_avg = sum(curr_confs) / len(curr_confs)
            past_confs = past.get(domain, [])
            past_avg = sum(past_confs) / len(past_confs) if past_confs else curr_avg
            velocity = round((curr_avg - past_avg) / _WINDOW_DAYS * 100, 4)  # % per day
            trend = "growing" if velocity > 0.01 else ("shrinking" if velocity < -0.01 else "stable")
            domains_result[domain] = {
                "current_conf": round(curr_avg, 3),
                "past_conf": round(past_avg, 3),
                "velocity_pct_per_day": velocity,
                "trend": trend,
            }
            velocities[domain] = velocity

        if velocities:
            result["fastest_learner"] = max(velocities, key=velocities.get)
            result["slowest_learner"] = min(velocities, key=velocities.get)
        result["domains"] = domains_result

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

    return result
