#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Helper operations for procedure_daemon."""
from __future__ import annotations

import json
from pathlib import Path
from pulse.core.brain_utils import read_jsonl_entries

def get_all_titles(filepath: Path, md_jsonl_map: dict) -> list[str]:
    """Extract ALL titles — JSONL first, MD fallback."""
    jsonl_path = md_jsonl_map.get(filepath)
    if jsonl_path:
        rows = read_jsonl_entries(jsonl_path)
        if rows:
            return [(r.get("title") or r.get("content", ""))[:200] for r in rows if r.get("title") or r.get("content")]
    if not filepath.exists():
        return []
    text = filepath.read_text(encoding="utf-8", errors="replace")
    sections = text.split("\n## ")
    return [s.split("\n")[0].strip() for s in sections[1:] if s.strip()]


def load_state(state_file: Path) -> dict:
    if state_file.exists():
        try:
            return json.loads(state_file.read_text(encoding="utf-8"))
        except Exception:
            pass
    return {"lesson_offset": 0, "pattern_offset": 0, "fail_offset": 0}


def save_state(state: dict, state_file: Path):
    try:
        state_file.write_text(json.dumps(state), encoding="utf-8")
    except Exception:
        pass
