"""
Phase 106: Decision Memory Enforcement Tools (Pillar II)

Provides tools for the Swarm to explicitly record architectural constraints and decisions.
These decisions are vectorized and injected into future prompts via the MemoryManager.
"""

from mcp.types import TextContent, Tool, ToolAnnotations

_SAFE_WRITE = ToolAnnotations(readOnlyHint=False, destructiveHint=False, idempotentHint=False, openWorldHint=False)

TOOLS = [
    Tool(
        name="broker_record_decision",
        description="Permanently record an architectural or technical decision constraint (e.g. 'Use Python 3.11, do not use 3.12 features' or 'We chose PostgreSQL because of JSONB'). This constraint will be automatically injected into future agents' prompts.",
        inputSchema={
            "type": "object",
            "properties": {
                "decision": {"type": "string", "description": "The decision made (e.g., 'Always use React for frontend')"},
                "context": {"type": "string", "description": "The situation or problem that led to this decision."},
                "rationale": {"type": "string", "description": "Why this specific decision was chosen."},
                "alternatives": {
                    "type": "array", 
                    "items": {"type": "string"},
                    "description": "What other options were considered and rejected."
                },
                "tags": {
                    "type": "array",
                    "items": {"type": "string"},
                    "description": "Tags for categorizing the decision (e.g., ['architecture', 'frontend', 'react'])."
                }
            },
            "required": ["decision", "context", "rationale"],
        },
        annotations=_SAFE_WRITE,
    )
]

def get_tools():
    return TOOLS

async def _handle_record_decision(args: dict) -> list[TextContent]:
    decision = args.get("decision")
    context = args.get("context")
    rationale = args.get("rationale")
    alternatives = args.get("alternatives", [])
    tags = args.get("tags", [])
    
    try:
        from pathlib import Path
        from runtime.memory.manager import MemoryManager
        data_dir = Path.home() / ".brynq"
        mm = MemoryManager(data_dir)
        
        doc_id = mm.decision_memory.log_decision(
            decision=decision,
            context=context,
            rationale=rationale,
            alternatives=alternatives,
            tags=tags
        )
        return [TextContent(type="text", text=f"Decision permanently recorded to Swarm Decision Memory (ID: {doc_id}). It will be enforced on all future prompts.")]
    except ImportError as e:
        return [TextContent(type="text", text=f"Error: Could not load MemoryManager. {e}")]
    except Exception as e:
        return [TextContent(type="text", text=f"Error saving decision: {e}")]

HANDLERS = {
    "broker_record_decision": _handle_record_decision,
}
