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

PROMPT = """\
{role}

<quick-start>
1. Read the existing artifacts for this job:
{artifacts}
2. Read the following project docs:
{docs}
3. Read the rules for creating tasks:
{rules}
4. Read the task template at """ + _TEMPLATE_PATH + """
5. Be ready to structure the task.
</quick-start>
{questions_section}

<steps>
1. Structure the following instructions into a task.md following the template:

<instructions>
{instructions}
</instructions>

2. Write the structured task to {task_path}
</steps>

<constraints>
- Follow the template structure exactly
- Create a clear, concise title for the task (the `# Title` heading) that captures the essence of the work
- Extract clear, specific, testable requirements from the instructions
- Preserve the intent of the original instructions — do not add scope beyond what is described
- The `name` field must be kebab-case, max 4 words
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
status: DONE
[NOTES]
Summary of the structured task.
</output-format>"""


async def run(*, instructions: str | None = None, **kwargs) -> str:
    """Structure instructions into a task.md file. Returns session_id."""
    ctx = get_context()
    model = MODEL

    task_path = ctx.paths["task_path"]

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

    questions_context = ctx.resolve_questions("task")
    questions_section = ""
    if questions_context:
        questions_section = (
            "<answered-questions>\n"
            "The following questions have been answered. You MUST implement these answers in your output.\n"
            f"{questions_context}"
            "</answered-questions>"
        )

    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 "",
        task_path=rel_path(task_path),
        questions_section=questions_section,
    )

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