"""Instructions for the vaultgen agent."""

import re
from pathlib import Path


def load_raw_context(vault: Path) -> str:
    """Load context from the ```context code block in config.md (Markdown)."""
    path = vault.joinpath("config.md")
    text = path.read_text()
    match = re.search(r"```context\s*\n(.*?)```", text, re.DOTALL)
    if not match:
        raise ValueError(f"No ```context``` block found in {path}")
    return match.group(1).strip()


def get_instructions(vault: Path) -> str:
    """Build agent instructions including all markdown file contents from the vault."""
    base = (
        "You are a powerful assistant with full access to an Obsidian vault. "
        "You can read, create, and update notes; follow schemas and templates; "
        "and help organize knowledge across the vault. Use the vault contents "
        "below as context—treat it as your working memory. When generating or "
        "editing notes, match the style and structure of existing content and "
        "respect any schema or conventions defined in the vault.\n\n"
        "To create a new note, output the given schema with the content you want; "
        "the note will be generated from it.\n\n"
        "To update a note, output the schema with the same name as the note "
        "to be updated; all content in that note will be overwritten.\n\n"
    )

    context = "**Context of the vault:**\n\n" + load_raw_context(vault) + "\n\n"

    parts = [base, context, "**Current state of the vault:**\n\n"]

    return "".join(parts)
