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}

<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 apply documentation updates.
</quick-start>

<steps>
1. Analyze what changed by reading the work report and comparing against existing doc.md files
2. Apply all documentation updates — edit the doc.md files directly
3. Maintain the update report at {update_path}, following the template structure
</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
- Only apply changes that reflect actual work completed — do not invent changes
- Keep documentation concise. Write for someone who needs to understand what this project does and how each part works — no unnecessary technical detail, no noise. If a piece of information doesn't help understanding, leave it out.
- Edit doc.md files in place — do not create new files, do not delete files
- Follow the update report template structure exactly
- Update `What Changed` to reflect all documentation changes made
- You MUST follow the exact output format below
</constraints>

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


async def run(*, instructions: str | None = None, **kwargs) -> str:
    """Apply doc updates based on completed work. Returns session_id."""
    ctx = get_context()
    model = MODEL

    work_path = ctx.paths["work_path"]
    update_path = ctx.paths["update_path"]

    role_lines = ["You are the Update Builder. You must read all provided inputs."]
    if Path(work_path).is_file():
        role_lines.append("Base your analysis on the completed work report.")
    if Path(update_path).is_file():
        role_lines.append(f"A previous version of {rel_path(update_path)} exists. Revise it based on the new inputs — do not start from scratch.")
    if instructions:
        role_lines.append("Follow the additional instructions provided.")
    role_lines.append("The instructions always take priority over other inputs.")
    role = "<role>\n" + "\n".join(role_lines) + "\n</role>"

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

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