from pathlib import Path
from mixersystem.data.repository import get_context, rel_path, MIXER_DIR
from mixersystem.data.agent_sdk import call_agent

_TEMPLATE_PATH = rel_path(str(MIXER_DIR / "workflows" / "refs" / "plan-template.md"))

PROMPT = """\
<role>
You are the Plan Builder. You create comprehensive technical implementation plans.
</role>

<quick-start>
1. Read the task file at {task_path}
2. Read the following project context:
{context}
3. Read the template at """ + _TEMPLATE_PATH + """
4. Be ready to design a thorough implementation plan.
</quick-start>

<steps>
1. Design a plan that addresses all requirements, following the template structure and rules
2. Write your complete plan to {plan_path}
</steps>

<constraints>
- Follow the template structure exactly
- Be thorough — this plan will be used by engineers to build the feature
</constraints>"""

RESUME_PROMPT = """\
<role>
You are the Plan Builder. You revise plans based on reviewer feedback.
</role>

<quick-start>
1. Read the plan at {plan_path}
2. Be ready to revise the plan.
</quick-start>

<steps>
1. Apply the following feedback:
{feedback}
2. Write the updated plan back to {plan_path}
</steps>

<constraints>
- Apply all feedback points
- Write the updated plan back to the same path
</constraints>"""

CONTEXT = ["doc", "structure", "rules"]
MODELS = {"S": "sonnet", "M": "opus", "L": "opus"}

_AGENT_NAME = Path(__file__).parent.parent.name + "/" + Path(__file__).stem


def _provider(provider: str | None = None) -> str:
    return provider or "claude"


async def run(*, provider: str | None = None, **kwargs) -> str:
    """Build a plan. Returns session_id."""
    ctx = get_context()
    chosen_provider = _provider(provider)
    model = MODELS.get(ctx.size, "opus")
    context = ctx.resolve_context(CONTEXT)
    prompt = PROMPT.format(
        task_path=rel_path(ctx.paths["task_path"]),
        context=context,
        plan_path=rel_path(ctx.paths["plan_path"]),
    )

    _, session_id = await call_agent(
        prompt=prompt,
        model=model,
        provider=chosen_provider,
        permission_mode="bypassPermissions",
        approval_mode="yolo",
        agent_name=_AGENT_NAME,
        **kwargs,
    )
    return session_id


async def run_resume(*, feedback: str, session_id: str,
                     provider: str | None = None, **kwargs) -> str:
    """Revise a plan based on feedback."""
    ctx = get_context()
    chosen_provider = _provider(provider)
    model = MODELS.get(ctx.size, "opus")
    prompt = RESUME_PROMPT.format(
        plan_path=rel_path(ctx.paths["plan_path"]),
        feedback=feedback,
    )

    _, next_session_id = await call_agent(
        prompt=prompt,
        model=model,
        provider=chosen_provider,
        permission_mode="bypassPermissions",
        approval_mode="yolo",
        agent_name=_AGENT_NAME,
        is_resume=True,
        session_id=session_id,
        **kwargs,
    )
    return next_session_id
