# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Agent trust I/O: load/save/bootstrap and agent discovery."""
import json
from pulse.core.brain_utils import STATE_DIR, LESSONS_JSONL, FAILS_JSONL, PATTERNS_JSONL, read_jsonl_entries
from pulse.core.brain_io import _acquire

TRUST_FILE = STATE_DIR / "agent_trust.json"


def _load_trust() -> dict:
    """Load state/agent_trust.json."""
    if not TRUST_FILE.exists():
        return {"agents": {}, "last_recomputed": ""}
    try:
        data = json.loads(TRUST_FILE.read_text(encoding="utf-8"))
        return data if isinstance(data, dict) else {"agents": {}, "last_recomputed": ""}
    except (json.JSONDecodeError, OSError):
        return {"agents": {}, "last_recomputed": ""}


def _save_trust(data: dict):
    """Save with filelock."""
    TRUST_FILE.parent.mkdir(parents=True, exist_ok=True)
    with _acquire(TRUST_FILE):
        TRUST_FILE.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")


def _bootstrap_trust(agent_name: str) -> tuple[float, str]:
    """Return cautious experiential bootstrap score (0.1)."""
    return 0.1, "untested"


def _collect_known_agents() -> set[str]:
    """Scan all JSONL brain files for unique agent names."""
    agents = set()
    for jsonl_path in (LESSONS_JSONL, FAILS_JSONL, PATTERNS_JSONL):
        try:
            for e in read_jsonl_entries(jsonl_path):
                src = e.get("agent", "") or e.get("source", "")
                if src and src != "unknown":
                    agents.add(src)
        except Exception:
            continue
    return agents
