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>
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 creating tasks:
{rules}
4. Read the specific instructions (if any):
{instructions}
5. Read the task template at """ + _TEMPLATE_PATH + """
6. 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>
- When reading files, ignore all content after `<!-- appendix -->` and inside `<ignore>` tags
- 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 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
- 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>"""


async def run(*, description: str, instructions: str | None = None, **kwargs) -> str:
    """Structure a raw description 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 description and description.strip():
        role_lines.append("Structure the provided description into a well-organized task.")
    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 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 "",
        description=description,
        task_path=rel_path(task_path),
    )

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