#!/usr/bin/env python3
# Copyright (c) 2026 PULSE Contributors. Proprietary. All rights reserved.
"""Work order and context builders for swarm autopilot agents."""
from __future__ import annotations

import os
import sys

from pulse.cli import ROOT_DIR, AGENTS_DIR


def _build_work_order(task_id, title, description, domain, brain_context,
                      skills_used=False, agent_id="unknown"):
    parts = []
    if brain_context:
        parts.append(
            "## BRAIN KNOWLEDGE -- READ THIS FIRST\\n"
            "These failures, lessons, and anti-patterns are FACTS, not suggestions.\\n\\n"
            f"{brain_context}"
        )
    loaded_skills = []
    try:
        sys.path.insert(0, str(AGENTS_DIR))
        from pulse.agents.pulse_wrapper import load_skills_for_domain
        skills_content, loaded_skills = load_skills_for_domain(
            domain, max_skills=2, skills_used=skills_used)
        if skills_content:
            parts.append(skills_content)
    except Exception:
        pass

    skills_tracking = ""
    if loaded_skills:
        skills_tracking = f" --skills-used \\\"{','.join(loaded_skills)}\\\""

    parts.append(
        f"## WORK ORDER\\n\\nTask ID: {task_id}\\nTitle: {title}\\n"
        f"Description: {description}\\nDomain: {domain}\\n\\n"
        "Instructions:\\n1. Read the relevant files\\n2. Apply brain knowledge\\n"
        "3. Make changes\\n4. Verify your changes work\\n"
        f"5. When done, output TASK_COMPLETE\\n\\n"
        f"{'When done, save with: python pulse/brain/pulse_save.py --agent ' + (agent_id or 'unknown') + ' --task-id ' + task_id + skills_tracking if task_id else ''}\\n\\n"
        "PROTECTED FILES -- DO NOT modify:\\n"
        "- Hippocampus/, Corpus_Callosum/, state/\\n"
        "- Prefrontal_Cortex/Action_Queue/task_board.json\\n"
        "- .env, .env.sig, PULSE_OS.md, Corpus_Callosum/CONSTITUTION.md"
    )
    return "\\n\\n".join(parts), loaded_skills


def _write_context_file(agent, agent_id, tier, work_order, task_query):
    context_path = ROOT_DIR / f"swarm_context_{agent_id}_{os.getpid()}.md"
    try:
        sys.path.insert(0, str(AGENTS_DIR))
        from pulse.agents.pulse_wrapper import build_context
        context, _ = build_context(
            include_constitution=True, search_lines=None,
            agent_name=agent, agent_tier=tier, autopilot=True,
            task_query=task_query, skills_used=False)
    except Exception:
        context = f"# PULSE Context\\nAgent: {agent_id}\\nTier: {tier}\\n"
    if work_order:
        context += f"\\n## WORK ORDER -- EXECUTE IMMEDIATELY\\n{work_order}\\n"
    context_path.write_text(context, encoding="utf-8")

    if work_order:
        title_line = ""
        for line in work_order.split("\\n"):
            if line.startswith("Title:"):
                title_line = line[6:].strip()
                break
        boot_msg = (
            f"WORK ORDER: Read {context_path.resolve()} and execute the task described inside. "
            f"Task: {title_line}. Do NOT modify task_board.json. When done, output TASK_COMPLETE."
        )
    else:
        boot_msg = (
            f"SYSTEM BOOT: Read {context_path.resolve()} IMMEDIATELY. "
            "Output a Status Report BEFORE using any tools."
        )
    return context_path, boot_msg
