#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Item 188: Near-miss learning loop — surface near-miss warnings for current domain.

Near-miss data (stored as patterns with 'near_miss' origin) feeds back into
search briefings so agents are warned when a domain has recent near-misses.
Fail-open: returns None on any error.
"""
import logging
from typing import Optional

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

_NEAR_MISS_RECENCY_DAYS = 7   # Only warn about near-misses in the last N days
_CONFIDENCE_THRESHOLD = 0.5   # Near-miss average confidence below this triggers warning


def _get_recent_near_miss_count(domain: str) -> int:
    """Count near-miss patterns for *domain* within the last _NEAR_MISS_RECENCY_DAYS days."""
    try:
        from pulse.core.brain_db import get_conn
        from datetime import datetime, timezone, timedelta
        cutoff = (datetime.now(timezone.utc) - timedelta(days=_NEAR_MISS_RECENCY_DAYS)).isoformat()
        conn = get_conn()
        row = conn.execute(
            "SELECT COUNT(*) FROM patterns WHERE domain=? AND timestamp>? "
            "AND (content LIKE '%near-miss%' OR content LIKE '%near_miss%' "
            "     OR content LIKE '%Near-miss%')",
            (domain, cutoff),
        ).fetchone()
        if row:
            return int(row[0])
    except Exception as e:
        log.debug("near-miss count query failed: %s", e)
    return 0


def _infer_domain_from_query(query: str) -> str:
    """Best-effort: return the first 'key' word from the query as a domain hint."""
    try:
        words = [w for w in query.lower().split() if len(w) >= 4]
        return words[0] if words else "general"
    except Exception:
        return "general"


def get_near_miss_warning(query: str, domain: str = "") -> Optional[str]:
    """Return a warning string if the query domain has recent near-misses, else None.

    Parameters
    ----------
    query:   The brain query text (used to infer domain when *domain* is blank).
    domain:  Explicit domain name; inferred from query if empty.

    Returns
    -------
    str warning or None.  Always fails open — never raises.
    """
    try:
        effective_domain = domain.strip() if domain.strip() else _infer_domain_from_query(query)
        if not effective_domain or effective_domain == "general":
            return None
        count = _get_recent_near_miss_count(effective_domain)
        if count > 0:
            return (
                f"!! NEAR-MISS WARNING: {count} near-miss event(s) logged in domain "
                f"'{effective_domain}' recently — verify brain knowledge before acting."
            )
    except Exception as e:
        log.debug("get_near_miss_warning failed: %s", e)
    return None
