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

_TEMPLATE_PATH = rel_path(str(MIXER_DIR / "workflows" / "update" / "update-template.md"))

PROMPT = """\
<role>
You are the Update Builder. You analyze completed work and suggest documentation updates.
</role>

<quick-start>
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 update template at """ + _TEMPLATE_PATH + """
5. 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>
- 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>"""

ACTION = "update"
MODEL = "L"

_AGENT_NAME = Path(__file__).parent.name + "/" + Path(__file__).stem


async def run(**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(ACTION),
        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
