# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""D14: Healer IO helpers — state, procedures, intents persistence.

Split from procedural_sleep_healer.py per Law 7.
"""
from __future__ import annotations

import json
from pathlib import Path

from pulse.core.brain_utils import (
    HIPPOCAMPUS_DIR, STATE_DIR, EVIDENCE_METRICS_DIR,
)
from pulse.core.brain_io import _acquire, save_json

STATE_FILE = STATE_DIR / "healer_state.json"
PROCEDURAL_LOG = EVIDENCE_METRICS_DIR / "procedural_log.json"
WANTS_FILE = HIPPOCAMPUS_DIR / "Intents" / "wants.json"
DONT_WANTS_FILE = HIPPOCAMPUS_DIR / "Intents" / "dont_wants.json"
CAPTURE_STATE = STATE_DIR / "auto_capture_state.json"
HISTORY_CAP = 50


def _load_json(path: Path) -> dict | list:
    if not path.exists():
        return {}
    try:
        return json.loads(path.read_text(encoding="utf-8"))
    except (json.JSONDecodeError, OSError):
        return {}


def _load_state() -> dict:
    s = _load_json(STATE_FILE)
    if not isinstance(s, dict):
        s = {}
    s.setdefault("runs", 0)
    s.setdefault("sweep_history", [])
    s.setdefault("promoted_ids", [])
    s.setdefault("tainted_items", [])
    s.setdefault("lifetime", {"stripped": 0, "tainted": 0, "promoted": 0})
    return s


def _save_state(state: dict) -> None:
    state["sweep_history"] = state.get("sweep_history", [])[-HISTORY_CAP:]
    STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
    with _acquire(STATE_FILE):
        save_json(STATE_FILE, state)


def _load_procedures() -> list[dict]:
    """Load procedure list from SQLite procedures table (JSON fallback)."""
    try:
        from pulse.core.brain_db import get_conn
        conn = get_conn()
        rows = conn.execute(
            "SELECT id, name, description, steps, domain, confidence, "
            "executions, successes FROM procedures"
        ).fetchall()
        if rows:
            result = []
            for r in rows:
                execs = r[6] or 0
                succ = r[7] or 0
                result.append({
                    "procedure_id": r[0],
                    "name": r[1],
                    "description": r[2] or "",
                    "event_sequence": json.loads(r[3] or "[]"),
                    "domain": r[4] or "general",
                    "confidence": float(r[5] or 0.5),
                    "executions": execs,
                    "success_rate": (succ / execs) if execs else 0.0,
                })
            return result
    except Exception:
        pass  # QR14: silent
    # JSON fallback (legacy procedural_log.json)
    data = _load_json(PROCEDURAL_LOG)
    return data.get("procedures", []) if isinstance(data, dict) else []


def _read_intents(path: Path) -> list[dict]:
    data = _load_json(path)
    return data if isinstance(data, list) else []


def _write_intents(path: Path, items: list[dict]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with _acquire(path):
        path.write_text(json.dumps(items, indent=2, ensure_ascii=False), encoding="utf-8")
