#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Section-rendering helpers for briefing.py — query expansion, relevance filtering,
source annotation, danger boost, and graph expansion logic.

Extracted from briefing.py for Law 7 SoC (files <= 300 lines).
"""
from __future__ import annotations


def apply_danger_boost(query: str, hits: dict, danger_words: list) -> None:
    """Boost confidence of anti_patterns/fails hits when danger words appear in query."""
    try:
        if any(dw in query.lower() for dw in danger_words):
            for src in ('anti_patterns', 'fails'):
                for h in hits.get(src, []):
                    h['confidence'] = min(1.0, h.get('confidence', 0.5) * 2.0)
                    h['_danger_boost'] = True
    except Exception:
        pass


def apply_relevance_filter(query: str, hits_flat: list, min_relevance: float = 0.15) -> list:
    """Post-retrieval relevance monitoring — drop items with very low similarity to query."""
    try:
        from pulse.core.brain_analysis import text_similarity as _text_sim
        filtered = []
        for h in hits_flat:
            htext = (h.get("text") or h.get("title") or h.get("content") or
                     h.get("description") or "")
            rel = _text_sim(query, htext)
            h["_relevance"] = round(rel, 4)
            if rel >= min_relevance:
                filtered.append(h)
        return filtered
    except Exception:
        return hits_flat


def annotate_source_labels(hits_flat: list) -> None:
    """N58: Annotate each hit with source attribution (agent + relative timestamp)."""
    try:
        from datetime import datetime, timezone as _tz
        now_utc = datetime.now(_tz.utc)

        def _rel_ts(ts_str: str) -> str:
            if not ts_str:
                return ""
            try:
                dt = datetime.fromisoformat(ts_str.replace("Z", "+00:00"))
                if dt.tzinfo is None:
                    dt = dt.replace(tzinfo=_tz.utc)
                diff = now_utc - dt
                secs = diff.total_seconds()
                if secs < 3600:
                    return f"{int(secs // 60)}m ago"
                if secs < 86400:
                    return f"{int(secs // 3600)}h ago"
                return f"{int(secs // 86400)}d ago"
            except Exception:
                return ""

        for h in hits_flat:
            agent = (h.get("agent") or h.get("source") or "")
            ts = (h.get("timestamp") or h.get("created_at") or "")
            h["_source_label"] = f"[{agent}, {_rel_ts(ts)}]" if agent or ts else ""
    except Exception:
        pass


def get_graph_expansions(query: str) -> list:
    """Expand query via SQLite graph edges (SEMANTIC/CAUSAL). Returns list of related texts."""
    expansions: list = []
    try:
        from pulse.core.brain_db import get_conn as _gc
        conn = _gc()
        exp: list = []
        for word in [w for w in query.split()[:2] if len(w) >= 4]:
            exp.extend(
                r[0] for r in conn.execute(
                    "SELECT gn2.text FROM graph_edges ge JOIN graph_nodes gn ON ge.from_node=gn.id "
                    "JOIN graph_nodes gn2 ON ge.to_node=gn2.id WHERE gn.text LIKE ? "
                    "AND ge.edge_type IN ('SEMANTIC','CAUSAL') LIMIT 2",
                    (f"%{word}%",)
                ).fetchall()
            )
        if exp:
            expansions = exp[:3]
    except Exception:
        pass
    return expansions


def apply_habituation(query: str, max_items: int, recent_queries: list,
                      threshold: int) -> int:
    """Reduce max_items when the same query repeats above threshold."""
    try:
        qn = query.lower().strip()
        recent_queries.append(qn)
        if len(recent_queries) > 10:
            recent_queries.pop(0)
        if sum(1 for q in recent_queries[-5:] if q == qn) >= threshold:
            return max(1, max_items // 2)
    except Exception:
        pass
    return max_items


def _compute_ignition_threshold() -> float:
    """Compute confidence ignition threshold, adapted to current agent load."""
    try:
        from pulse.core.interoception import get_signals as _gs
        return min(0.3 + (_gs().get('agent_load', 0) * 0.05), 0.8)
    except Exception:
        return 0.4
