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 / "update-template.md"))
MODEL = "L"
_AGENT_NAME = "update_builder"

PROMPT = """\
<role>
You are the Update Builder. You analyze completed work and suggest documentation updates.
</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 existing artifacts for this job:
{artifacts}
2. Read the following project docs:
{docs}
3. Read the rules for updating docs:
{rules}
4. Read the specific instructions (if any):
{instructions}
5. Read the update template at """ + _TEMPLATE_PATH + """
6. Be ready to suggest documentation updates.
</quick-start>

<steps>
1. Analyze what changed by reading the work report and comparing against existing doc.md files
2. Identify which doc.md files need updating based on the changes
3. Write structured update suggestions to {update_path}, following the template
</steps>

<constraints>
- When reading files, ignore all content after `<!-- appendix -->` and inside `<ignore>` tags
- Follow the template structure exactly
- Only suggest changes that reflect actual work completed — do not invent changes
- Reference specific doc.md file paths
- Suggest concrete content, not vague instructions
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
status: DONE
[NOTES]
Summary of suggested documentation updates.
</output-format>"""


async def run(*, instructions: str | None = None, **kwargs) -> str:
    """Analyze work and suggest doc updates. Returns session_id."""
    ctx = get_context()
    model = MODEL

    prompt = PROMPT.format(
        artifacts=ctx.resolve_artifacts(),
        docs=ctx.resolve_docs(),
        rules=ctx.resolve_rules(_AGENT_NAME.split("_", 1)[0]),
        instructions=instructions or "",
        update_path=rel_path(ctx.paths["update_path"]),
    )

    _, session_id = await call_agent(
        prompt=prompt,
        model=model,
        agent_name=_AGENT_NAME,
        **kwargs,
    )
    return session_id
