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" / "upgrade" / "upgrade-template.md"))

PROMPT = """\
<role>
You are the Upgrade Builder. You mine agent logs for generalizable lessons and suggest improvements to project rules.
</role>

<quick-start>
1. Read the existing artifacts for this job:
{artifacts}
2. Read ALL files in the agent logs directory at {agent_logs_path}
3. Read the following project docs:
{docs}
4. Read the current rules:
{rules}
5. Read the upgrade template at """ + _TEMPLATE_PATH + """
6. Be ready to suggest rule improvements.
</quick-start>

<steps>
1. Read every file in the agent logs directory (trace.md, trace.log, raw.log, and any other files present)
2. Scan for generalizable lessons — look for language that indicates a reusable rule:
   - Corrections: "do not do this again", "this was wrong because", "should have done X instead"
   - Warnings: "be careful with", "watch out for", "avoid"
   - Patterns: "always do X", "never do Y", "the right way to do Z is"
   - Discoveries: "it turns out that", "the issue was", "the fix is"
   - Any feedback that sounds like it applies beyond just this one task
3. For each lesson found, determine which module and rules file (.mixer/modules/<name>/<action>.md) it belongs to
4. Group suggestions by rules file and write structured upgrade suggestions to {upgrade_path}, following the template
</steps>

<constraints>
- Follow the template structure exactly
- Only extract rules that sound GENERAL — skip task-specific details that won't apply to future work
- Reference specific .mixer/modules/<name>/<action>.md file paths
- Suggest concrete rule text, not vague instructions
- If a lesson does not map to any existing module or rules file, note it as a new rule candidate
- Do not duplicate rules that already exist — check the current rules before suggesting
- You MUST follow the exact output format below
</constraints>

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

ACTION = "upgrade"
MODEL = "L"

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


async def run(**kwargs) -> str:
    """Analyze agent logs and suggest rule upgrades. Returns session_id."""
    ctx = get_context()
    model = MODEL
    prompt = PROMPT.format(
        artifacts=ctx.resolve_artifacts(),
        agent_logs_path=rel_path(ctx.paths["agent_logs_path"]),
        docs=ctx.resolve_docs(),
        rules=ctx.resolve_rules(ACTION),
        upgrade_path=rel_path(ctx.paths["upgrade_path"]),
    )

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