"""Prompt template generation for orchestrate plan and merge phases."""

from __future__ import annotations

from vibepod.core.orchestrate.plan_file import OrchestratePlan

COMPLETION_INSTRUCTION = """\
When you have finished all your work, write the following JSON to the file \
at the path stored in the VP_STATUS_FILE environment variable:

  {"status": "done", "summary": "<one sentence summary>", "files_changed": ["path/to/file", ...]}

If you cannot complete the task, write:

  {"status": "failed", "reason": "<why it failed>"}

Do not exit or stop until you have written this file."""

_PLAN_FORMAT_EXAMPLE = """\
# VibePod Orchestration Plan

## Meta
- **run-id**: {run_id}
- **created**: <ISO timestamp>

## Task
<original task description>

## Sub-tasks

### [TASK-1] <Sub-task title>
- **persona**: <persona name>
- **agent**: <agent> (fallback: <fallback agent>)
- **worktree**: .vibepod/worktrees/task-1
- **prompt-file**: .vibepod/tasks/task-1.md
- **depends-on**: none
- **status**: pending

### [TASK-2] <Sub-task title>
- **persona**: <persona name>
- **agent**: <agent> (fallback: <fallback agent>)
- **worktree**: .vibepod/worktrees/task-2
- **prompt-file**: .vibepod/tasks/task-2.md
- **depends-on**: TASK-1
- **status**: pending"""


def build_planning_prompt(
    task: str,
    personas: dict,
    run_id: str,
) -> str:
    """Build the planning prompt for the controller agent."""
    persona_lines = []
    for name, cfg in personas.items():
        desc = cfg.get("description", "")
        caps = cfg.get("capabilities", [])
        preferred = cfg.get("preferred", "")
        fallback = cfg.get("fallback", "")
        fb_str = f" (fallback: {fallback})" if fallback else ""
        caps_str = "\n".join(f"  - {c}" for c in caps)
        persona_lines.append(
            f"**{name}** — preferred agent: {preferred}{fb_str}\n"
            f"  {desc}\n{caps_str}"
        )

    persona_block = "\n\n".join(persona_lines)
    plan_example = _PLAN_FORMAT_EXAMPLE.format(run_id=run_id)

    return f"""\
You are a software engineering orchestrator. Your job is to break down the \
following task into sub-tasks and assign each sub-task to the most suitable \
persona from the list below. Then write a PLAN.md file.

## Task
{task}

## Available Personas
{persona_block}

## Instructions

1. Analyse the task and identify the independent sub-tasks required.
2. For each sub-task, pick the best-fitting persona from the list above.
3. Identify dependencies between sub-tasks (which must complete before others can start).
4. For each sub-task, write a detailed task prompt file to \
`.vibepod/tasks/task-N.md`. Each task prompt must end with the following \
completion instruction exactly as written:

{COMPLETION_INSTRUCTION}

5. Write `.vibepod/PLAN.md` using exactly the following format \
(replace placeholder text; do not change field names or markdown structure):

{plan_example}

Use `depends-on: none` if a task has no dependencies. For multiple \
dependencies, use comma-separated task IDs (e.g. `TASK-1, TASK-2`).

Write all files now. Do not ask questions. Start immediately.
"""


def build_merge_prompt(plan: OrchestratePlan, workspace: str) -> str:
    """Build the merge prompt for the controller agent."""
    task_lines = []
    for task in plan.tasks:
        if task.status != "done":
            continue
        branch = f"orchestrate/{task.id.lower()}-{plan.run_id}"
        summary = getattr(task, "summary", "")
        summary_line = f" — {summary}" if summary else ""
        task_lines.append(f"- **{task.id}** ({branch}): {task.title}{summary_line}")

    tasks_block = "\n".join(task_lines)

    return f"""\
You are a software engineering orchestrator. Multiple worker agents have \
completed sub-tasks on separate git branches. Your job is to merge all \
branches into the current branch to produce a coherent result.

## Original Task
{plan.task_description}

## Completed Sub-tasks
{tasks_block}

## Instructions

1. For each branch listed above, run `git merge <branch>` to merge it into \
the current branch.
2. Resolve any merge conflicts that arise. Prefer keeping the intent of \
both changes where possible.
3. After all merges are complete, verify the codebase is in a consistent \
state (check imports, obvious syntax errors, etc.).
4. If you cannot resolve a conflict, leave the conflict markers in place, \
write a brief note about the conflict to `.vibepod/merge-conflicts.md`, \
and continue with the remaining branches.
5. Commit after each successful merge with a message like \
`merge: integrate TASK-N results`.

Begin merging now. Do not ask questions.
"""
