"""Task router — determines which project module(s) a task affects.

Moved from workflows/task/agents/ to data layer so it can be called
from both workflow orchestrators and Studio pre-flight checks.
"""

from mixersystem.data.repository import (
    get_context, rel_path, parse_result, read_session_json, update_session_json,
)
from mixersystem.data.agent_sdk import call_agent

MODEL = "M"
_AGENT_NAME = "task_router"

PROMPT = """\
<role>
You are the Task Router. You determine which project module(s) a task affects.
</role>

<quick-start>
1. Read the task at {task_path}
2. Read the following project docs:
{docs}
3. Be ready to identify affected modules.
</quick-start>

<steps>
1. Determine which module(s) the task affects based on the requirements and the context above
2. If the task targets specific modules, return their names as a comma-separated list
3. If the task spans all modules or is not module-specific, return "all"
</steps>

<constraints>
- Return a comma-separated list of module names, or "all"
- Base your decision on the task requirements and the project's module structure
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
status: DONE
modules: <comma-separated module names or "all">
[NOTES]
Brief explanation of why these modules were selected.
</output-format>"""


async def run() -> str:
    """Identify affected module(s) for a task. Returns response text."""
    ctx = get_context()
    model = MODEL
    prompt = PROMPT.format(
        task_path=rel_path(ctx.paths["task_path"]),
        docs=ctx.resolve_docs(),
    )

    response, _ = await call_agent(
        prompt=prompt,
        model=model,
        permission_mode="plan",
        agent_name=_AGENT_NAME,
    )
    return response


async def resolve_modules(session_folder: str) -> list[str]:
    """Run the task_router agent and return resolved modules.

    Writes the result to session.json and returns the module list.
    """
    ctx = get_context()
    response = await run()
    result = parse_result(response)
    raw = result.get("modules", "all")

    # Parse into list
    if isinstance(raw, str):
        modules = [m.strip() for m in raw.split(",") if m.strip()]
    else:
        modules = raw

    update_session_json(session_folder, modules=modules, modules_locked=True)
    return modules
