#!/usr/bin/env python3
"""CLI commands for mcp-server-nucleus."""

import os
import json
import sys
import argparse
from pathlib import Path

# ============================================================================
# TEMPLATE: DEFAULT (Full structure)
# ============================================================================
DEFAULT_STATE = {
    "version": "1.0.0",
    "current_sprint": {
        "name": "Sprint 1",
        "focus": "Getting Started with Nucleus",
        "started_at": None
    },
    "top_3_leverage_actions": [
        "Set up your first agent",
        "Configure triggers",
        "Connect to Claude Desktop"
    ]
}

DEFAULT_TRIGGERS = {
    "version": "1.0.0",
    "triggers": [
        {
            "event_type": "task_completed",
            "target_agent": "synthesizer",
            "emitter_filter": None
        },
        {
            "event_type": "research_done",
            "target_agent": "architect",
            "emitter_filter": ["researcher"]
        }
    ]
}

SAMPLE_AGENT = '''# {agent_name} Agent

## Role
Define what this agent does.

## Responsibilities
- Task 1
- Task 2

## Triggers
Activated when: [define trigger conditions]

## Output Format
Describe expected output format.
'''

# ============================================================================
# TEMPLATE: SOLO (Minimal structure for solo founders)
# ============================================================================
SOLO_STATE = {
    "version": "1.0.0",
    "mode": "solo",
    "current_focus": "Getting started with Nucleus",
    "tasks": []
}

SOLO_THREAD_REGISTRY = '''# Thread Registry

> **Protocol:** Agents check this file on activation to know their role.
> **Stable Anchor:** Thread ID (UUID) never changes, even when IDE renames the thread.

---

## Active Threads

| Thread ID | Role | Focus |
|:----------|:-----|:------|
| *(Add your threads here)* | | |

---

## How to Use

1. **Find your thread ID** in your IDE's artifact path (e.g., `.gemini/antigravity/brain/<thread-id>/`)
2. **Add a row** to the table above with your role
3. **Agent self-identifies** on next activation by reading this registry

---

## Example

| Thread ID | Role | Focus |
|:----------|:-----|:------|
| `7c654df4-b83e-...` | Lead Systems Architect | Infrastructure, MCP |
| `853a0b7e-9052-...` | Synthesizer | Product work, orchestration |
'''

SOLO_CONTEXT = '''# Project Context

> This file provides context to all AI agents working on your project.

## Company/Project
- **Name:** [Your Project Name]
- **Description:** [What you're building]

## Technical Stack
- **Backend:** 
- **Frontend:** 
- **Database:** 

## Current Priorities
1. 
2. 
3. 
'''


def init_brain_default(brain_path: Path) -> bool:
    """Initialize with default (full) template."""
    dirs = [
        brain_path / "ledger",
        brain_path / "artifacts" / "research",
        brain_path / "artifacts" / "strategy",
        brain_path / "agents",
        brain_path / "memory",
    ]
    
    for d in dirs:
        d.mkdir(parents=True, exist_ok=True)
        print(f"  📁 Created {d}")
    
    (brain_path / "ledger" / "state.json").write_text(
        json.dumps(DEFAULT_STATE, indent=2)
    )
    print(f"  📄 Created ledger/state.json")
    
    (brain_path / "ledger" / "triggers.json").write_text(
        json.dumps(DEFAULT_TRIGGERS, indent=2)
    )
    print(f"  📄 Created ledger/triggers.json")
    
    (brain_path / "ledger" / "events.jsonl").write_text("")
    print(f"  📄 Created ledger/events.jsonl")
    
    (brain_path / "agents" / "synthesizer.md").write_text(
        SAMPLE_AGENT.format(agent_name="Synthesizer")
    )
    print(f"  🤖 Created agents/synthesizer.md")
    
    (brain_path / "memory" / "context.md").write_text(
        "# Project Context\n\nDescribe your project here.\n"
    )
    print(f"  📝 Created memory/context.md")
    
    return True


def init_brain_solo(brain_path: Path) -> bool:
    """Initialize with solo (minimal) template."""
    dirs = [
        brain_path / "ledger",
        brain_path / "meta",
        brain_path / "memory",
    ]
    
    for d in dirs:
        d.mkdir(parents=True, exist_ok=True)
        print(f"  📁 Created {d}")
    
    (brain_path / "ledger" / "state.json").write_text(
        json.dumps(SOLO_STATE, indent=2)
    )
    print(f"  📄 Created ledger/state.json (solo mode)")
    
    (brain_path / "meta" / "thread_registry.md").write_text(SOLO_THREAD_REGISTRY)
    print(f"  📋 Created meta/thread_registry.md")
    
    (brain_path / "memory" / "context.md").write_text(SOLO_CONTEXT)
    print(f"  📝 Created memory/context.md")
    
    return True


def init_brain(path: str = ".brain", template: str = "default"):
    """Initialize a new .brain directory structure."""
    brain_path = Path(path)
    
    if brain_path.exists():
        print(f"⚠️  Directory {path} already exists.")
        response = input("Overwrite? (y/N): ")
        if response.lower() != 'y':
            print("Aborted.")
            return False
    
    print(f"🧠 Initializing Nuclear Brain at {path}/ (template: {template})...")
    
    # Route to template-specific init
    if template == "solo":
        init_brain_solo(brain_path)
    else:
        init_brain_default(brain_path)
    
    print(f"\n✅ Nuclear Brain initialized!")
    
    # Generate config and auto-configure
    abs_path = str(brain_path.absolute())
    nucleus_config = {
        "command": "python3",
        "args": ["-m", "mcp_server_nucleus"],
        "env": {"NUCLEAR_BRAIN_PATH": abs_path}
    }
    
    # Attempt auto-configuration for Claude Desktop
    claude_config_path = Path.home() / "Library" / "Application Support" / "Claude" / "claude_desktop_config.json"
    auto_configured = False
    
    if claude_config_path.exists():
        try:
            print(f"\n🔍 Found Claude Desktop config...")
            backup_path = claude_config_path.with_suffix(".json.bak")
            if not backup_path.exists():
                import shutil
                shutil.copy2(claude_config_path, backup_path)
                print(f"  📦 Created backup at {backup_path}")
            
            with open(claude_config_path, 'r') as f:
                config_data = json.load(f)
            
            if "mcpServers" not in config_data:
                config_data["mcpServers"] = {}
            
            if "nucleus" not in config_data["mcpServers"]:
                config_data["mcpServers"]["nucleus"] = nucleus_config
                
                with open(claude_config_path, 'w') as f:
                    json.dump(config_data, f, indent=2)
                
                print(f"  ✅ Auto-configured 'nucleus' in Claude Desktop settings!")
                auto_configured = True
            else:
                print(f"  ℹ️  'nucleus' already configured in Claude Desktop.")
                auto_configured = True
                
        except Exception as e:
            print(f"  ⚠️  Could not auto-configure: {e}")

    if not auto_configured:
        config_snippet = f'''"nucleus": {{
    "command": "python3",
    "args": ["-m", "mcp_server_nucleus"],
    "env": {{
      "NUCLEAR_BRAIN_PATH": "{abs_path}"
    }}
  }}'''
        
        print(f"\n" + "="*60)
        print(f"📋 COPY THIS into your AI client's config:")
        print(f"="*60)
        print()
        print(config_snippet)
        print()
        print(f"="*60)
        print(f"\n📍 Config file locations:")
        print(f"   Claude Desktop: ~/Library/Application Support/Claude/claude_desktop_config.json")
        print(f"   Cursor:         ~/.cursor/mcp.json") 
        print(f"   Windsurf:       ~/.codeium/windsurf/mcp_config.json")
    
    print(f"\n💡 Next Step: Restart your AI Client and ask:")
    print(f"   'What's my current focus?'")
    
    return True


def main():
    """CLI entry point."""
    parser = argparse.ArgumentParser(
        prog='nucleus-init',
        description='Initialize a Nuclear Brain for your project'
    )
    parser.add_argument(
        'command',
        nargs='?',
        default='init',
        help='Command to run (default: init)'
    )
    parser.add_argument(
        'path',
        nargs='?',
        default='.brain',
        help='Path to create .brain directory (default: .brain)'
    )
    parser.add_argument(
        '-t', '--template',
        choices=['default', 'solo'],
        default='default',
        help='Template to use: default (full) or solo (minimal)'
    )
    
    args = parser.parse_args()
    
    if args.command == 'init':
        init_brain(args.path, args.template)
    else:
        # Unknown command, show help
        parser.print_help()


if __name__ == "__main__":
    main()
