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 / "upgrade-template.md"))
MODEL = "L"
_AGENT_NAME = "upgrade_builder"

PROMPT = """\
{role}

<quick-start>
1. Read the existing artifacts for this job:
{artifacts}
2. Read ALL files in the logs directory at {logs_path}
3. Read the following project docs:
{docs}
4. Read the current rules:
{rules}
5. Read the specific instructions (if any):
{instructions}
6. Read the upgrade template at """ + _TEMPLATE_PATH + """
7. Be ready to apply rule improvements.
</quick-start>
{questions_section}

<steps>
1. Read every file in the logs directory (agent_trace.log, agent_raw.log, and any other files present)
2. Mine the logs for signals that indicate a generalizable lesson. Focus on these concrete sources:
   - **Reviewer rejections** — when a review agent returns NEEDS_WORK, the reason often points to a rule that should exist. Look at what the reviewer flagged and why.
   - **Test failures and fixes** — when the tester fails and the builder retries, the diff between what was wrong and what fixed it reveals patterns worth codifying.
   - **User instructions** — the `instructions` parameter carries explicit user guidance (e.g. "focus on performance", "don't use X"). If the instruction sounds general, it's a rule candidate.
   - **Retry prompts** — when an agent had to be retried (missing [RESULT] block, format issues), that may indicate the agent's rules need clearer output format guidance.
   - **Builder self-corrections** — when a builder says "I should have done X instead" or changes approach mid-response, the corrected approach is the lesson.
   - **Repeated patterns** — if the same kind of fix or feedback appears multiple times across agents, that's a strong signal for a rule.
3. For each lesson found, determine which module and rules file (.mixer/rules/<action>/<module>.md) it belongs to
4. Apply all rule improvements — edit or create the .mixer/rules/ files directly
5. Maintain the upgrade report at {upgrade_path}, following the template structure
</steps>

<constraints>
- Only extract rules that sound GENERAL — skip task-specific details that won't apply to future work
- Keep rules concise. Each rule should be short and actionable — no filler, no redundancy. If it doesn't help the builder do better work, leave it out.
- Edit or create .mixer/rules/<action>/<module>.md files directly — apply the rules, do not just suggest them
- If a rules file does not exist yet, create it
- Do not duplicate rules that already exist — check the current rules before writing
- Follow the upgrade report template structure exactly
- Update `What Changed` to reflect all rule changes made
- You MUST follow the exact output format below
</constraints>

<output-format>
[RESULT]
status: DONE
[NOTES]
Summary of rule upgrades applied.
</output-format>"""


async def run(*, instructions: str | None = None, **kwargs) -> str:
    """Apply rule upgrades based on agent log analysis. Returns session_id."""
    ctx = get_context()
    model = MODEL

    logs_path = ctx.paths["logs_path"]
    upgrade_path = ctx.paths["upgrade_path"]

    role_lines = ["You are the Upgrade Builder. You must read all provided inputs."]
    logs_dir = Path(logs_path)
    if logs_dir.is_dir() and any(logs_dir.iterdir()):
        role_lines.append("Analyze all log files for generalizable lessons.")
    if Path(upgrade_path).is_file():
        role_lines.append(f"A previous version of {rel_path(upgrade_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("upgrade")
    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(),
        logs_path=rel_path(logs_path),
        docs=ctx.resolve_docs(),
        rules=ctx.resolve_rules(_AGENT_NAME.split("_", 1)[0]),
        instructions=instructions or "",
        upgrade_path=rel_path(upgrade_path),
        questions_section=questions_section,
    )

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