"""Shared text utilities for MEMORY.md block parsing.

Used by tools/memory_tools.py and memory_consolidator.py.
"""
from __future__ import annotations

import os
import re

SECTION_HEADER_RE = re.compile(r"^##\s+.+$", re.MULTILINE)


def read_memory_file(abs_path: str) -> str:
    """Read full content of a memory file. Returns empty string if missing."""
    if not os.path.exists(abs_path) or not os.path.isfile(abs_path):
        return ""
    try:
        with open(abs_path, "r", encoding="utf-8") as f:
            return f.read()
    except Exception:
        return ""


def split_into_blocks(content: str) -> list[tuple[str, str]]:
    """Split content into (header_line, body) blocks.

    Each block is either a ## section or leading text.
    Returns list of (header_or_empty, body).
    """
    if not content.strip():
        return []
    parts = SECTION_HEADER_RE.split(content)
    headers = SECTION_HEADER_RE.findall(content)
    blocks = []
    if parts and parts[0].strip():
        blocks.append(("", parts[0].strip()))
    for i, header in enumerate(headers):
        body = (parts[i + 1] if i + 1 < len(parts) else "").strip()
        blocks.append((header.strip(), body))
    return blocks


def blocks_to_content(blocks: list[tuple[str, str]]) -> str:
    """Serialize blocks back to file content."""
    out = []
    for header, body in blocks:
        if header:
            out.append(header)
            if body:
                out.append(body)
            out.append("")
        else:
            if body:
                out.append(body)
                out.append("")
    return "\n".join(out).strip() + ("\n" if out else "")
