#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
# See LICENSE file for details.
"""
PULSE Neural Interface Daemon
Generates ACTIVE_NEURAL_STATE.md from current session evidence.

Rendering logic delegated to neural_render.py (split for Law 7).
"""
import json
import sys
import time
from datetime import datetime, timezone
from pathlib import Path

SCRIPT_DIR = Path(__file__).resolve().parent
ROOT_DIR = SCRIPT_DIR.parent.parent.parent

# When run directly, ensure pulse package is importable
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from pulse.core.brain_utils import load_json
from pulse.admin.brain_ops.brain_recommender import generate_recommendation

# Re-export rendering functions for backward compat
from pulse.daemons.neural.neural_render import (  # noqa: F401
    _compress_learnings, _summarize_strategy, _summarize_tasks,
    _render_state, _truncate, _strip_front_matter, _extract_sections,
    _summarize_section, _learning_paths, _parse_front_matter,
    _weight_from_frontmatter, _now_iso,
    LEARNING_DIRS, STRATEGIC_INTENTS_FILE,
)

EVIDENCE_FILE = ROOT_DIR / "Hippocampus" / "Evidence" / "Sessions" / "current_session.json"
OUTPUT_DIR = ROOT_DIR / "Prefrontal_Cortex" / "Working_Memory"
OUTPUT_FILE = OUTPUT_DIR / "ACTIVE_NEURAL_STATE.md"
STATE_FILE = ROOT_DIR / "state" / "pulse_neural_state.json"
POLL_INTERVAL = 1.0


def _load_state():
    if not STATE_FILE.exists():
        return {"mtime": 0.0}
    try:
        return json.loads(STATE_FILE.read_text(encoding="utf-8"))
    except Exception:
        return {"mtime": 0.0}


def _save_state(state: dict):
    STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
    STATE_FILE.write_text(json.dumps(state), encoding="utf-8")


def _latest_query(items: list) -> str:
    # Prefer WANT, then OBSERVATION, then DONT_WANT
    for t in ("WANT", "OBSERVATION", "DONT_WANT"):
        for item in reversed(items):
            if item.get("type") == t:
                return item.get("description", "").strip()
    return ""


def _latest_dont_wants(items: list, limit: int = 3) -> list:
    out = []
    for item in reversed(items):
        if item.get("type") == "DONT_WANT":
            desc = item.get("description", "").strip()
            if desc:
                out.append(desc)
        if len(out) >= limit:
            break
    return out


def _write_state(content: str):
    OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
    OUTPUT_FILE.write_text(content, encoding="utf-8")


class PulseNeural:
    def __init__(self, verbose=False):
        self.verbose = verbose
        self.state = _load_state()

    def _evidence_changed(self) -> bool:
        if not EVIDENCE_FILE.exists():
            return False
        mtime = EVIDENCE_FILE.stat().st_mtime
        if mtime == self.state.get("mtime"):
            return False
        self.state["mtime"] = mtime
        return True

    def run(self):
        print("[PULSE] Neural Interface running...")
        while True:
            try:
                if self._evidence_changed():
                    items = load_json(EVIDENCE_FILE)
                    if not isinstance(items, list):
                        items = []
                    query = _latest_query(items)
                    rec = generate_recommendation(query) if query else {}
                    donts = _latest_dont_wants(items)
                    learnings = _compress_learnings()
                    content = _render_state(query, rec, donts, learnings)
                    _write_state(content)
                    _save_state(self.state)
                    if self.verbose:
                        print("[PULSE] ACTIVE_NEURAL_STATE updated")
                time.sleep(POLL_INTERVAL)
            except Exception as e:
                if self.verbose:
                    print(f"[PULSE] Neural Interface error: {e}")
                time.sleep(POLL_INTERVAL)


if __name__ == "__main__":
    v = "--verbose" in sys.argv or "-v" in sys.argv
    PulseNeural(verbose=v).run()
