# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Briefing render helpers: adversarial injection, surprise/predictive signals, column summary.

Split from briefing_signals.py for Law 7 compliance.
"""
from __future__ import annotations


def adversarial_injection(lines: list, all_hits_flat: list) -> None:
    """P3-2: Adversarial injection — inject random failure from same domain."""
    if "PAST FAIL" not in " ".join(lines):
        try:
            _adv_dom = all_hits_flat[0].get("domain", "general") if all_hits_flat else "general"
            try:
                from pulse.brain.metacognition.metamemory import get_metamemory as _gmm
                _adv_n = 2 if _gmm().get(_adv_dom, {}).get("competence_level") == "expert" else 1
            except Exception:
                _adv_n = 1
            from pulse.core.brain_db import get_conn as _gc_adv
            _conn_adv = _gc_adv()
            _adv_rows = (
                _conn_adv.execute(
                    "SELECT content FROM failures WHERE domain=? ORDER BY RANDOM() LIMIT ?",
                    (_adv_dom, _adv_n)
                ).fetchall()
                or _conn_adv.execute(
                    "SELECT content FROM failures ORDER BY RANDOM() LIMIT ?", (_adv_n,)
                ).fetchall()
            )
            for _r in _adv_rows:
                lines.append(f"  ! ADVERSARIAL FAIL: {_r[0][:100]}")
        except Exception:
            pass


def surprise_detection(lines: list, results: dict) -> None:
    """Item 46 (P13): Exogenous attention -- insert SURPRISE at top if contradiction found."""
    try:
        for _src46, _sh46 in results.get("results", {}).items():
            if not isinstance(_sh46, list):
                continue
            for _h46 in _sh46:
                if _h46.get("_contradiction_flag") and float(_h46.get("confidence", 0)) > 0.6:
                    lines.insert(
                        0,
                        "!! SURPRISE: High-confidence contradiction found -- "
                        + (_h46.get("text", "") or _h46.get("content", ""))[:80]
                    )
                    return
    except Exception:
        pass


def predictive_triage(lines: list, all_hits_flat: list) -> None:
    """Item 47 (P13): Predictive triage -- warn on items approaching failure threshold."""
    try:
        from pulse.core.brain_db import get_conn as _get_conn_triage
        _td = (all_hits_flat[0].get("domain", "general") if all_hits_flat else "general")
        _dec = _get_conn_triage().execute(
            "SELECT content FROM lessons WHERE confidence < 0.4 AND confidence > 0.1 "
            "AND domain = ? ORDER BY confidence ASC LIMIT 2", (_td,)
        ).fetchall()
        if _dec:
            lines.append(
                f"!! PREDICTIVE TRIAGE: {len(_dec)} items approaching failure threshold in domain '{_td}'"
            )
    except Exception:
        pass


def cortical_columns_summary(results: dict, _org_columns) -> list:
    """Item 187: Cortical columns -- append domain-group summary."""
    extra = []
    try:
        if _org_columns is not None and results.get("results"):
            _col_data = _org_columns(results["results"])
            _cols = _col_data.get("columns", {})
            if len(_cols) >= 2:
                _col_summary = ", ".join(
                    f"{dom}({v['column_size']})" for dom, v in list(_cols.items())[:5]
                )
                extra.append(f"  # COLUMNS: {_col_summary}")
    except Exception:
        pass
    return extra


def render_predictions_and_warnings(hits: dict) -> list:
    """Render predictions, anti-patterns, and failures sections."""
    section_lines = []
    for h in hits.get("predictions", [])[:2]:
        text = (h.get("title") or h.get("text", ""))[:120].strip()
        body = h.get("text", "")[:200]
        if text:
            section_lines.append(f"  !! PREDICTION: {text}")
            if len(body) > len(text):
                section_lines.append(f"     -> {body}")
    for h in hits.get("anti_patterns", [])[:2]:
        text = (h.get("title") or h.get("text", ""))[:100].strip()
        if text:
            section_lines.append(f"  ! ANTI-PATTERN: {text}")
    for h in hits.get("fails", [])[:2]:
        text = (h.get("text") or h.get("title", ""))[:100].strip()
        if text:
            section_lines.append(f"  ! PAST FAIL: {text}")
    return section_lines
