"""CLAUDE.md auto-regeneration for the sovereign agent.

Provides generate_claude_md() as the canonical public API for producing
CLAUDE.md content from live agent state, and write_claude_md() for
persisting it to disk.

Delegates to context_loader for data gathering and formatting so that
all four formatters (text, json, claude-md, cursor-rules) stay in one
place while this module acts as the dedicated entry-point for CLAUDE.md
generation.

Usage:
    from skcapstone.claude_md import generate_claude_md, write_claude_md
    from pathlib import Path

    md = generate_claude_md(Path("~/.skcapstone").expanduser())
    write_claude_md(Path("~/.skcapstone").expanduser(), Path("CLAUDE.md"))
"""

from __future__ import annotations

import logging
from pathlib import Path

logger = logging.getLogger("skcapstone.claude_md")

# Auto-generation header written into every file so readers know the source.
_AUTO_HEADER = (
    "This file is auto-generated by `skcapstone context --format claude-md`.\n"
    "It gives Claude Code persistent context about the sovereign agent."
)


def generate_claude_md(home: Path, memory_limit: int = 10) -> str:
    """Generate CLAUDE.md content from current agent state.

    Gathers live data (identity, pillars, board, recent memories,
    consciousness status) and formats it as Markdown suitable for Claude
    Code's CLAUDE.md persistent context file.

    Args:
        home: Agent home directory (typically ``~/.skcapstone``).
        memory_limit: Maximum number of recent memories to embed.

    Returns:
        Full CLAUDE.md contents as a string.
    """
    from .context_loader import format_claude_md, gather_context

    ctx = gather_context(home, memory_limit=memory_limit)
    return format_claude_md(ctx)


def write_claude_md(
    home: Path,
    dest: Path,
    memory_limit: int = 10,
    *,
    backup: bool = False,
) -> None:
    """Generate and write CLAUDE.md to *dest*.

    If *backup* is True and *dest* already exists, the existing file is
    renamed to ``<dest>.bak`` before writing.

    Args:
        home: Agent home directory (typically ``~/.skcapstone``).
        dest: Destination file path (e.g. ``Path("CLAUDE.md")``).
        memory_limit: Maximum number of recent memories to embed.
        backup: Rename existing file to .bak before overwriting.
    """
    content = generate_claude_md(home, memory_limit=memory_limit)

    dest = dest.expanduser().resolve()

    if backup and dest.exists():
        bak = dest.with_suffix(".md.bak")
        dest.rename(bak)
        logger.info("Backed up existing %s → %s", dest, bak)

    dest.write_text(content, encoding="utf-8")
    logger.info("Wrote CLAUDE.md to %s (%d bytes)", dest, len(content))
