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" / "task" / "task-template.md"))

PROMPT = """\
<role>
You are the Task Builder. You structure raw task descriptions into well-organized task.md files.
</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>

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

<description>
{description}
</description>

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

<constraints>
- Follow the template structure exactly
- Extract clear, specific, testable requirements from the raw description
- Preserve the intent of the original description — do not add scope beyond what is described
- The `name` field must be kebab-case, max 4 words (used for git branches)
- If modules are specified, set them in the `modules` frontmatter field
- You MUST follow the exact output format below
</constraints>

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

ACTION = "task"
MODEL = "L"

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


async def run(*, description: str, **kwargs) -> str:
    """Structure a raw description into a task.md file. Returns session_id."""
    ctx = get_context()
    model = MODEL
    prompt = PROMPT.format(
        artifacts=ctx.resolve_artifacts(),
        docs=ctx.resolve_docs(),
        rules=ctx.resolve_rules(ACTION),
        description=description,
        task_path=rel_path(ctx.paths["task_path"]),
    )

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