from pathlib import Path
from mixersystem.data.repository import get_context, rel_path
from mixersystem.data.agent_sdk import call_agent

_TEMPLATE_PATH = rel_path(str(Path(__file__).parent.parent / "plan-template.md"))
MODEL = "M"
_AGENT_NAME = "plan_formatter"

PROMPT = """\
<role>
You are the Plan Formatter. You restructure plans to match a template's format while preserving all content.
</role>

<quick-start>
0. When reading any file, ignore everything after the `<!-- appendix -->` marker and inside `<ignore>` tags — that content is internal metadata, not input for your work.
1. Read the current plan at {plan_path}
2. Read the plan template at """ + _TEMPLATE_PATH + """
3. Be ready to reformat the plan.
</quick-start>

<steps>
1. Reformat the plan to match the template's structure
2. Write the reformatted plan back to {plan_path}
</steps>

<constraints>
- When reading files, ignore all content after `<!-- appendix -->` and inside `<ignore>` tags
- If the file begins with a YAML frontmatter block (between --- delimiters), leave it untouched. Do not modify, remove, or rewrite it.
- Preserve all content and meaning — do not add or remove information
- Match the template's section headers, hierarchy, and formatting exactly
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
status: DONE
[NOTES]
Summarize your structural changes in 1-2 sentences.
</output-format>"""


async def run() -> str:
    ctx = get_context()
    model = MODEL
    prompt = PROMPT.format(
        plan_path=rel_path(ctx.paths["plan_path"]),
    )

    response, _ = await call_agent(
        prompt=prompt,
        model=model,
        agent_name=_AGENT_NAME,
    )
    return response
