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

_TEMPLATE_PATH = rel_path(str(Path(__file__).parent / "work-template.md"))
MODEL = "L"
_AGENT_NAME = "work_builder"

PROMPT = """\
{role}

<quick-start>
1. Read the existing artifacts for this job:
{artifacts}
2. Read the following project docs:
{docs}
3. Read the rules for building:
{rules}
4. Read the specific instructions (if any):
{instructions}
5. Read the work report template at """ + _TEMPLATE_PATH + """
6. Be ready to implement.
</quick-start>
{questions_section}

<steps>
1. Implement all changes — create and modify files as needed
2. Maintain the work report at {work_path}, following the template structure
</steps>

<constraints>
- If a plan is provided, follow it exactly — implement every file and change it specifies
- Follow ALL rules files listed below
- Write every file specified in the plan (if provided) — do not skip any
- Do NOT run tests — testing is handled by a separate tester agent, not by you. Even if the plan includes test steps, skip them. Your job is implementation only.
- Do NOT deviate from the plan's architecture or approach (if a plan is provided)
- Follow the work report template structure exactly
- Update `What Changed` to reflect the complete current implementation state (not only this run's delta)
- Append exactly one new entry to `Revision History` for this run ({run_index}/{max_test_iterations})
- Revision history is not only tester-feedback fixes; include internal revisions and discoveries too
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
status: DONE
[NOTES]
Summary of what was implemented.
</output-format>"""

RESUME_PROMPT = """\
<role>
You are the Work Builder. You fix issues based on tester feedback.
</role>

<quick-start>
1. Read the plan at {plan_path}
2. Read the work report template at """ + _TEMPLATE_PATH + """
3. Be ready to fix the issues.
</quick-start>

<steps>
1. Apply the following feedback:
{feedback}
2. Fix all issues mentioned in the feedback
3. Update the work report at {work_path}, following the template structure
</steps>

<constraints>
- Apply all feedback points
- Re-read the plan if needed to ensure compliance
- Follow the work report template structure exactly
- Update `What Changed` to reflect the complete current implementation state (not only this run's delta)
- Append exactly one new entry to `Revision History` for this run ({run_index}/{max_test_iterations})
- Revision history is not only tester-feedback fixes; include internal revisions and discoveries too
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
status: DONE
[NOTES]
Summary of what was fixed.
</output-format>"""


async def run(*, provider: str = "claude", run_index: int = 1,
              max_test_iterations: int = 5,
              instructions: str | None = None, **kwargs) -> str:
    """Implement code from a plan. Returns session_id."""
    ctx = get_context()
    model = MODEL

    plan_path = ctx.paths["plan_path"]
    work_path = ctx.paths["work_path"]

    role_lines = ["You are the Work Builder. You must read all provided inputs."]
    if Path(plan_path).is_file():
        role_lines.append("Follow the plan exactly.")
    if Path(work_path).is_file():
        role_lines.append(f"A previous version of {rel_path(work_path)} exists. Revise it based on the new inputs — do not start from scratch.")
    if instructions:
        role_lines.append("Follow the additional instructions provided.")
    role_lines.append("The instructions always take priority over other inputs.")
    role = "<role>\n" + "\n".join(role_lines) + "\n</role>"

    questions_context = ctx.resolve_questions("work")
    questions_section = ""
    if questions_context:
        questions_section = (
            "<answered-questions>\n"
            "The following questions have been answered. You MUST implement these answers in your output.\n"
            f"{questions_context}"
            "</answered-questions>"
        )

    extra_prompt = PROMPT.format(
        role=role,
        artifacts=ctx.resolve_artifacts(),
        docs=ctx.resolve_docs(),
        rules=ctx.resolve_rules(_AGENT_NAME.split("_", 1)[0]),
        instructions=instructions or "",
        work_path=rel_path(work_path),
        run_index=run_index,
        max_test_iterations=max_test_iterations,
        questions_section=questions_section,
    )

    _, session_id = await call_agent(
        prompt=extra_prompt,
        model=model,
        provider=provider,
        agent_name=_AGENT_NAME,
        **kwargs,
    )
    return session_id


async def run_resume(*, feedback: str, session_id: str,
                     provider: str = "claude",
                     run_index: int = 1, max_test_iterations: int = 5,
                     **kwargs) -> str:
    """Fix code based on tester feedback. Returns session_id."""
    ctx = get_context()
    model = MODEL
    extra_prompt = RESUME_PROMPT.format(
        plan_path=rel_path(ctx.paths["plan_path"]),
        feedback=feedback,
        work_path=rel_path(ctx.paths["work_path"]),
        run_index=run_index,
        max_test_iterations=max_test_iterations,
    )

    _, session_id = await call_agent(
        prompt=extra_prompt,
        model=model,
        provider=provider,
        agent_name=_AGENT_NAME,
        is_resume=True,
        session_id=session_id,
        **kwargs,
    )
    return session_id
