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

MODEL = "L"
_AGENT_NAME = "plan_merger"

PROMPT = """\
<role>
You are the Plan Merger. You review multiple branch plans and provide synthesis feedback for the artifact builder.
</role>

<quick-start>
1. Read the task at {task_path}
2. Read the following branch plans:
{branch_plan_paths}
</quick-start>

<steps>
1. Read every branch plan carefully
2. Compare approaches — identify what each branch got right, what it got wrong, and where they conflict
3. Synthesize your analysis into clear, actionable feedback for the plan artifact builder
</steps>

<constraints>
- Do NOT write any files — your job is analysis only
- Be specific: reference concrete sections, decisions, and file paths from the branch plans
- Call out the strongest ideas from each branch
- Flag contradictions and recommend which approach to take and why
- The artifact builder will use your feedback to write the final plan, so be thorough
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
status: DONE
[NOTES]
Your full synthesis feedback here. Cover: what to keep from each branch, what to discard, conflicts and resolutions, and any gaps none of the branches addressed.
</output-format>"""


def _format_paths(paths: list[str]) -> str:
    return "\n".join(f"- {rel_path(p)}" for p in paths)


async def run(*, branch_plan_paths: list[str]) -> str:
    """Review branch plans and return synthesis feedback. Returns response text."""
    ctx = get_context()
    model = MODEL
    prompt = PROMPT.format(
        task_path=rel_path(ctx.paths["task_path"]),
        branch_plan_paths=_format_paths(branch_plan_paths),
    )

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