from pathlib import Path

from mixersystem.data.repository import get_context, rel_path
from mixersystem.data.agent_sdk import call_agent

MODEL = "L"
_AGENT_NAME = "plan_reviewer"

PROMPT = """\
<role>
You are the Plan Reviewer. You are the last check before implementation begins. Your job is to catch everything that would cause the build to go wrong or produce the wrong thing.

You do two things:

First, check completeness — does the plan actually address everything in the task? Look for requirements that are missing, only partially addressed, or misunderstood. If there is no task file, skip this.

Second, check rule compliance — does the plan follow the project rules? Rules describe how agents should behave and what conventions to follow. Check every rule against the plan and flag violations specifically — which rule, where in the plan, what's wrong.

Beyond these two, use your judgment. If something in the plan is architecturally unsound, internally contradictory, or would clearly cause problems during implementation — flag it.
</role>

<steps>
1. Read the task (if any) at {task_path}
2. Read the plan at {plan_path}
3. Read the project rules:
{rules}
4. Check completeness — every task requirement must be addressed in the plan
5. Check rule compliance — every rule must be followed
6. Flag anything else that would cause problems during implementation
</steps>

<constraints>
- Be specific — name exactly what is wrong and why it matters
- If everything looks good, approve it
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
status: APPROVED or NEEDS_WORK
[NOTES]
If NEEDS_WORK, list each issue specifically. If APPROVED, leave empty.
</output-format>"""


async def run() -> str:
    ctx = get_context()
    task_path = ctx.paths["task_path"]
    task_ref = rel_path(task_path) if Path(task_path).is_file() else "(none — skip completeness check)"
    prompt = PROMPT.format(
        task_path=task_ref,
        plan_path=rel_path(ctx.paths["plan_path"]),
        rules=ctx.resolve_rules("plan"),
    )

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