#!/usr/bin/env python3
"""
Execution Mode Detector Hook
Implements Context-Aware Execution Modes from Claude Collective v9.4.2

Detects whether the user prompt indicates coordination mode (planning, reporting,
validation) or implementation mode (writing source code) and sets appropriate context.
"""

import datetime
import json
import os
import sys
from pathlib import Path


def detect_execution_mode(prompt: str) -> str:
    """Analyze the prompt to determine the execution mode."""

    # Keywords that indicate COORDINATION mode
    coordination_keywords = [
        "plan",
        "planning",
        "strategy",
        "analyze",
        "review",
        "discuss",
        "explain",
        "describe",
        "evaluate",
        "assess",
        "report",
        "status",
        "breakdown",
        "epic",
        "task",
        "contract",
        "validate",
        "verify",
        "architecture",
        "design",
        "wireframe",
        "mockup",
        "requirements",
        "specification",
        "documentation",
        "meeting",
        "coordination",
    ]

    # Keywords that indicate IMPLEMENTATION mode
    implementation_keywords = [
        "write",
        "code",
        "implement",
        "build",
        "create",
        "develop",
        "fix",
        "debug",
        "refactor",
        "optimize",
        "function",
        "class",
        "component",
        "feature",
        "bug",
        "commit",
        "deploy",
        "test",
        "unittest",
        "integration",
        "api",
        "endpoint",
        "database",
    ]

    # Phrases that indicate specific modes
    coordination_phrases = [
        "make a plan",
        "create plan",
        "think about",
        "how should",
        "what do you think",
        "analyze the",
        "review the",
        "explain how",
        "break down",
        "create epic",
        "define contract",
        "ui mockup",
        "wireframe for",
        "design the interface",
    ]

    implementation_phrases = [
        "write code",
        "implement the",
        "create function",
        "build component",
        "fix the bug",
        "add feature",
        "write test",
        "create class",
        "develop api",
        "write script",
    ]

    prompt_lower = prompt.lower()

    # Check for explicit mode indicators
    if any(phrase in prompt_lower for phrase in coordination_phrases):
        return "coordination"

    if any(phrase in prompt_lower for phrase in implementation_phrases):
        return "implementation"

    # Count keyword occurrences
    coordination_score = sum(
        1 for keyword in coordination_keywords if keyword in prompt_lower
    )
    implementation_score = sum(
        1 for keyword in implementation_keywords if keyword in prompt_lower
    )

    # Determine mode based on scores
    if implementation_score > coordination_score:
        return "implementation"
    elif coordination_score > implementation_score:
        return "coordination"
    else:
        # Default to coordination for ambiguous cases
        return "coordination"


def get_token_budget_allocation(mode: str) -> dict[str, str]:
    """Return token budget allocation based on execution mode."""
    if mode == "coordination":
        return {
            "core_instructions": "20%",
            "agent_coordination": "30%",
            "context_memory": "35%",
            "output_generation": "15%",
        }
    else:  # implementation
        return {
            "core_instructions": "10%",
            "agent_coordination": "5%",
            "context_memory": "45%",
            "output_generation": "40%",
        }


def create_mode_context_file(mode: str, budget_allocation: dict[str, str]) -> str:
    """Create a context file with mode information."""
    context_dir = Path(".claude/context")
    context_dir.mkdir(parents=True, exist_ok=True)

    context_file = context_dir / "execution_mode.md"

    budget_lines = "\n".join(
        f"- {k.replace('_', ' ').title()}: {v}" for k, v in budget_allocation.items()
    )

    coordination_guidelines = """
Focus on:
- Planning and strategic thinking
- Breaking down problems into epics and tasks
- Agent coordination and task assignment
- Validation and reporting
- Architecture and design decisions
- Creating contracts and specifications

Token efficiency is prioritized. Maximize planning quality while minimizing token usage.
"""

    implementation_guidelines = """
Focus on:
- Writing high-quality, complete source code
- Implementing features according to contracts
- Performing mandatory self-validation (HEPHAESTUS protocol)
- Writing comprehensive tests (TDD approach)
- Code quality and correctness over token efficiency

Output quality and completeness are prioritized. Use available context for
implementation details.
"""

    guidelines = (
        coordination_guidelines if mode == "coordination" else implementation_guidelines
    )

    content = f"""# Current Execution Mode: {mode.upper()}

## Token Budget Allocation
{budget_lines}

## Mode Guidelines

### {mode.upper()} Mode
{guidelines}

Generated at: {datetime.datetime.now().isoformat()}
"""

    with open(context_file, "w", encoding="utf-8") as f:
        f.write(content)

    return str(context_file)


def main() -> None:
    try:
        input_data = json.load(sys.stdin)
    except json.JSONDecodeError as e:
        print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
        sys.exit(1)

    prompt = input_data.get("prompt", "")

    if not prompt:
        sys.exit(0)

    # Detect execution mode
    mode = detect_execution_mode(prompt)
    budget_allocation = get_token_budget_allocation(mode)

    print(f"🎯 MODE DETECTOR: Detected {mode.upper()} mode")

    # Create context file for the session
    context_file = create_mode_context_file(mode, budget_allocation)

    # Set environment variable for other processes
    os.environ["CLAUDE_COLLECTIVE_MODE"] = mode

    # Provide mode-specific guidance
    if mode == "coordination":
        guidance = """
🧠 ATHENA/HERMES MODE ACTIVE

Focus on efficient planning and coordination:
- Break down complex problems into clear epics
- Define contracts before implementation
- Use subagents for detailed investigation
- Prioritize token efficiency
- Create actionable task assignments
"""
    else:
        guidance = """
🔨 HEPHAESTUS MODE ACTIVE

Focus on high-quality implementation:
- Write complete, working code
- Follow TDD approach (tests first)
- Perform mandatory static analysis
- Include comprehensive error handling
- Validate against contracts
- Document implementation decisions
"""

    print(guidance)
    print(f"📊 Token budget optimized for {mode} mode")
    print(f"📄 Mode context saved to {context_file}")

    sys.exit(0)


if __name__ == "__main__":
    main()
