#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""Helper functions for pulse_relay — brain check and status display.


Split from pulse_relay.py per Law 7.
Dependencies: Python stdlib only (Law 4)
"""
import logging
log = logging.getLogger("pulse.tasks.relay_helpers")

from pulse.core.brain_utils import TASK_BOARD_FILE, load_json_dict


def brain_check(prompt: str) -> None:
    """QR13: Query brain before dispatch — surface relevant failures/anti-patterns.
    Fails open silently; never blocks relay execution."""
    try:
        from pulse.brain.brain_search.search_engine import brain_search
        results = brain_search(prompt[:120], max_per_source=3)
        hits = [h for src in results.get("results", {}).values()
                if isinstance(src, list) for h in src
                if float(h.get("confidence", 0)) >= 0.6]
        if hits:
            print(f"[RELAY] Brain: {len(hits)} relevant items found for this task.")
            for h in hits[:2]:
                text = (h.get("content") or h.get("text") or "")[:100]
                print(f"  [{h.get('type','?')}] {text}")
    except Exception as _exc:
        pass  # QR14: silent — consider log.debug("%s", _exc)


def show_status() -> None:
    """Print current task board summary."""
    board = load_json_dict(TASK_BOARD_FILE)
    dispatches = board.get("dispatches", [])

    if not dispatches:
        print("[RELAY] Task board is empty. Use pulse_relay.py to dispatch work.")
        return

    total = 0
    by_status = {}
    for dispatch in dispatches:
        print(f"\nDispatch: {dispatch.get('dispatch_id', '?')}")
        print(f"  Prompt: {dispatch.get('prompt', '?')[:120]}")
        print(f"  Posted: {dispatch.get('dispatched_at', '?')}")
        for t in dispatch.get("tasks", []):
            total += 1
            status = t.get("status", "?")
            by_status[status] = by_status.get(status, 0) + 1
            claimed = t.get("claimed_by", "")
            claim_info = f" -> {claimed}" if claimed else ""
            print(f"    [{status}]{claim_info} {t['task_id']}: {t.get('title', '?')}")

    print(f"\nTotal: {total} tasks | " + " | ".join(f"{s}: {c}" for s, c in sorted(by_status.items())))
