#!/usr/bin/env python3
"""
Claude Multi-Agent PM Framework - Pure Python CLI Entry Point

This is the pure Python implementation that replaces the mixed JavaScript/Python
architecture. All CLI functionality is now implemented in Python using Click.
"""

import sys
import os
import subprocess
import shutil
from datetime import datetime
from pathlib import Path

# Script version - tracks claude-pm script updates independently
def get_script_version():
    """Get script version - injected during deployment."""
    return "017"

SCRIPT_VERSION = get_script_version()

# Check for package installation first
def check_package_installation():
    """Check if claude-multiagent-pm is installed as a package."""
    try:
        import claude_pm
        return Path(claude_pm.__file__).parent.parent
    except ImportError:
        return None

# Add the framework path to Python path for imports
# Dynamic framework path detection
def detect_framework_path():
    """Detect the framework path dynamically."""
    script_path = Path(__file__).resolve()
    
    # Check if we're in a symlinked environment
    if script_path.is_symlink():
        # If this is a symlink, resolve to the actual location
        actual_script_path = script_path.resolve()
        potential_framework = actual_script_path.parent.parent
        
        # Verify this is actually a framework directory
        if (potential_framework / "claude_pm").exists():
            return potential_framework
    
    # Check if we're in ~/.local/bin (deployed via symlink)
    if script_path.parent == Path.home() / ".local" / "bin":
        # Look for framework in typical locations
        framework_candidates = [
            # Check for deprecated source mode first
            Path.home() / "Projects" / "claude-multiagent-pm",
            Path.home() / ".claude-pm",
        ]
        
        # Check if deprecated source mode is being used
        deprecated_path = Path.home() / "Projects" / "claude-multiagent-pm"
        if deprecated_path.exists() and (deprecated_path / "claude_pm").exists():
            # Console not available yet - warnings will be shown later
            # console.print("[yellow]⚠️  DEPRECATION WARNING: Detected editable installation[/yellow]")
            # console.print("[yellow]   Source directory usage is deprecated and will be removed in v2.0[/yellow]")
            # console.print("[yellow]   Please install from PyPI: pip install claude-multiagent-pm[/yellow]")
            # console.print("[dim]   Set CLAUDE_PM_SOURCE_MODE=deprecated to suppress this warning[/dim]")
            # console.print("")
            
            # Allow deprecated mode with environment variable
            # if os.environ.get("CLAUDE_PM_SOURCE_MODE") == "deprecated":
            return deprecated_path
        
        for candidate in framework_candidates:
            if (candidate / "claude_pm").exists():
                return candidate
    
    # Check if we're in development mode (bin directory within framework)
    if (script_path.parent.parent / "claude_pm").exists():
        return script_path.parent.parent
    
    # NEW: Check npm global directory for fresh machine installs
    try:
        # Get npm global directory using npm root -g command
        npm_global_result = subprocess.run(
            ["npm", "root", "-g"], 
            capture_output=True, 
            text=True, 
            timeout=10
        )
        
        if npm_global_result.returncode == 0:
            npm_global_root = Path(npm_global_result.stdout.strip())
            npm_framework_path = npm_global_root / "@bobmatnyc" / "claude-multiagent-pm"
            
            # Check if framework files exist in npm global location
            if (npm_framework_path / "claude_pm").exists():
                return npm_framework_path
            
            # Also check for framework template specifically for CLAUDE.md copying
            if (npm_framework_path / "framework" / "CLAUDE.md").exists():
                return npm_framework_path
                
    except (subprocess.TimeoutExpired, FileNotFoundError, Exception):
        # npm command failed or not available - continue with other detection methods
        pass
    
    # Check if package is installed first
    package_path = check_package_installation()
    if package_path:
        return package_path
    
    # Fallback to ~/.claude-pm
    return Path.home() / ".claude-pm"

framework_path = detect_framework_path()

sys.path.insert(0, str(framework_path))

try:
    import click
    from rich.console import Console
except ImportError:
    print("❌ Missing required dependencies. Please install:")
    print("   pip install click rich")
    sys.exit(1)

console = Console()


def get_framework_version(framework_path_override=None):
    """Get framework version from multiple sources."""
    # Use provided framework path or global one
    fw_path = framework_path_override or framework_path
    
    # First try to get version from installed Python package
    try:
        import claude_pm
        return claude_pm.__version__
    except (ImportError, AttributeError):
        pass
    
    # For deployed version, check config.json first
    config_json = Path.home() / ".claude-pm" / "config.json"
    if config_json.exists():
        try:
            import json
            with open(config_json) as f:
                data = json.load(f)
                version = data.get("version")
                if version:
                    return version
        except (json.JSONDecodeError, KeyError):
            pass
    
    # Try package.json in framework path
    package_json = fw_path / "package.json"
    if package_json.exists():
        try:
            import json
            with open(package_json) as f:
                data = json.load(f)
                if data.get("name") == "@bobmatnyc/claude-multiagent-pm":
                    return data.get("version", "unknown")
        except (json.JSONDecodeError, KeyError):
            pass
    
    # Try VERSION file in framework path
    version_file = fw_path / "VERSION"
    if version_file.exists():
        try:
            return version_file.read_text().strip()
        except OSError:
            pass
    
    # NEW: Try to detect version from npm global install
    try:
        npm_global_result = subprocess.run(
            ["npm", "root", "-g"], 
            capture_output=True, 
            text=True, 
            timeout=10
        )
        
        if npm_global_result.returncode == 0:
            npm_global_root = Path(npm_global_result.stdout.strip())
            npm_package_json = npm_global_root / "@bobmatnyc" / "claude-multiagent-pm" / "package.json"
            
            if npm_package_json.exists():
                try:
                    import json
                    with open(npm_package_json) as f:
                        data = json.load(f)
                        if data.get("name") == "@bobmatnyc/claude-multiagent-pm":
                            return data.get("version", "unknown")
                except (json.JSONDecodeError, KeyError):
                    pass
    except (subprocess.TimeoutExpired, FileNotFoundError, Exception):
        pass
    
    return "unknown"


def get_script_path():
    """Get the actual script path that's being executed."""
    try:
        # Use shutil.which to find the actual claude-pm executable in PATH
        script_path = shutil.which("claude-pm")
        if script_path:
            return script_path
        
        # Fallback to current script location
        return str(Path(__file__).resolve())
        
    except Exception:
        # If all else fails, return current file location
        return str(Path(__file__).resolve())


def detect_deployment_type():
    """Detect the deployment type and framework path."""
    script_path = Path(__file__).resolve()
    
    # Check if this script is deployed in ~/.local/bin
    local_bin = Path.home() / ".local" / "bin"
    if script_path.parent == local_bin:
        return {
            "type": "deployed", 
            "framework_path": framework_path,
            "script_path": script_path.parent
        }
    
    # Check if this script is in the framework directory
    if "claude-multiagent-pm" in str(script_path):
        return {
            "type": "development",
            "framework_path": framework_path,
            "script_path": script_path.parent
        }
    
    # Default fallback
    return {
        "type": "unknown",
        "framework_path": framework_path,
        "script_path": script_path.parent
    }


def validate_framework_deployment():
    """Validate that Claude PM Framework is properly deployed per ISS-0112."""
    # ENHANCED: More flexible validation that works with auto-installation
    
    # Primary check: Does ~/.claude-pm/ directory exist?
    claude_pm_dir = Path.home() / ".claude-pm"
    if not claude_pm_dir.exists():
        return False
    
    # Check for config.json with required keys
    config_file = claude_pm_dir / "config.json"
    if config_file.exists():
        try:
            import json
            with open(config_file) as f:
                config = json.load(f)
            
            # If config exists and has installationComplete=true, trust it
            if config.get("installationComplete", False):
                return True
            
            # If config exists but installationComplete is false/missing, check minimal requirements
            if "installType" in config and "version" in config:
                # Config file exists with basic info - consider deployed even if not marked complete
                return True
                
        except (json.JSONDecodeError, OSError):
            # Config file exists but is malformed - continue with fallback checks
            pass
    
    # FALLBACK: Check for essential framework components that indicate successful deployment
    essential_indicators = [
        claude_pm_dir / "agents",  # Agent hierarchy should exist
        claude_pm_dir / "templates",  # Templates directory
        framework_path / "claude_pm",  # Python package should be available
    ]
    
    # If at least 2 out of 3 essential indicators exist, consider it deployed
    existing_indicators = sum(1 for indicator in essential_indicators if indicator.exists())
    if existing_indicators >= 2:
        return True
    
    # ALTERNATIVE: Check if we can import the Python package (indicates successful installation)
    try:
        import subprocess
        test_import = subprocess.run([
            sys.executable, "-c", "import claude_pm; print('OK')"
        ], capture_output=True, text=True, timeout=5)
        
        if test_import.returncode == 0 and "OK" in test_import.stdout:
            # Python package is importable - framework is functional
            return True
            
    except (subprocess.TimeoutExpired, FileNotFoundError, Exception):
        # Import test failed - continue with existing validation
        pass
    
    # FINAL FALLBACK: Basic directory structure check
    # If ~/.claude-pm exists and has any subdirectories, consider it partially deployed
    if claude_pm_dir.exists():
        subdirs = [p for p in claude_pm_dir.iterdir() if p.is_dir()]
        if len(subdirs) > 0:
            # Directory has content - likely a valid deployment
            return True
    
    return False


def find_claude_md_in_hierarchy():
    """
    Find the highest CLAUDE.md file in the directory hierarchy.
    Returns the path to the highest CLAUDE.md file or None if not found.
    """
    current = Path.cwd()
    
    # Walk up the directory tree
    while current != current.parent:  # Stop at root
        claude_md = current / "CLAUDE.md"
        if claude_md.exists() and claude_md.is_file():
            return claude_md
        current = current.parent
    
    # Check root directory
    root_claude_md = current / "CLAUDE.md"
    if root_claude_md.exists() and root_claude_md.is_file():
        return root_claude_md
    
    return None


def check_parent_claude_md_status():
    """
    Check parent directory CLAUDE.md file status against framework template.
    Now automatically performs backup and update when framework is newer.
    
    Returns:
        Dict with check results:
        - needs_update: bool - True if parent file needs updating
        - parent_exists: bool - True if parent CLAUDE.md exists
        - parent_path: Path - Path to parent CLAUDE.md file
        - template_version: str - Framework template version
        - parent_version: str - Parent file version (if available)
        - status_message: str - Human-readable status description
        - auto_updated: bool - True if automatic update was performed
        - backup_path: str - Path to backup file (if created)
    """
    try:
        # First check if CLAUDE.md exists anywhere in the hierarchy
        existing_claude_md = find_claude_md_in_hierarchy()
        
        # Get current working directory and look for parent CLAUDE.md
        current_dir = Path.cwd()
        parent_dir = current_dir.parent
        parent_claude_md = parent_dir / "CLAUDE.md"
        
        # Get framework template path - try multiple locations
        framework_template = None
        template_locations = [
            framework_path / "framework" / "CLAUDE.md",
            Path.home() / ".claude-pm" / "templates" / "CLAUDE.md",
            Path(__file__).parent.parent / "framework" / "CLAUDE.md",
        ]
        
        for location in template_locations:
            if location.exists():
                framework_template = location
                break
        
        # Check if framework template exists
        if not framework_template:
            return {
                "needs_update": False,
                "parent_exists": parent_claude_md.exists(),
                "parent_path": parent_claude_md,
                "template_version": "unknown",
                "parent_version": "unknown",
                "status_message": "Framework template not found - cannot check for updates",
                "auto_updated": False,
                "backup_path": None
            }
        
        # Extract template version from framework template
        template_version = "unknown"
        try:
            template_content = framework_template.read_text()
            # SIMPLIFIED VERSIONING APPROACH (as of 2025-07-20):
            # - We use a single serial number for framework versions (e.g., "015")
            # - The VERSION file contains this single number
            # - CLAUDE_MD_VERSION in the template matches the VERSION file exactly
            # - FRAMEWORK_VERSION gets replaced with the same value during deployment
            # - This eliminates confusion from two-part versions like "015-003"
            # The comparison logic checks if parent_version != template_version
            version_file = framework_path / "framework" / "VERSION"
            if version_file.exists():
                template_version = version_file.read_text().strip()
        except Exception:
            pass
        
        # Check if parent CLAUDE.md exists
        if not parent_claude_md.exists():
            # Check if CLAUDE.md exists higher up in the hierarchy
            if existing_claude_md:
                console.print(f"[dim]📄 CLAUDE.md already exists at: {existing_claude_md}[/dim]")
                console.print(f"[dim]   Skipping auto-deployment to avoid duplication[/dim]")
                return {
                    "needs_update": False,
                    "parent_exists": False,
                    "parent_path": parent_claude_md,
                    "template_version": template_version,
                    "parent_version": "none",
                    "status_message": f"CLAUDE.md exists higher in hierarchy at {existing_claude_md.parent.name}",
                    "auto_updated": False,
                    "backup_path": None,
                    "hierarchy_claude_md": existing_claude_md
                }
            
            # ENHANCED: Auto-deploy CLAUDE.md when missing
            try:
                console.print(f"[yellow]📄 No CLAUDE.md found in hierarchy - auto-deploying framework template[/yellow]")
                
                # Perform automatic deployment using Parent Directory Manager
                backup_result, update_result = perform_automatic_backup_and_update(
                    current_dir, parent_claude_md, template_version, quiet_mode=True
                )
                
                if update_result:
                    auto_updated = True
                    status_message = f"✅ Auto-deployed CLAUDE.md version {template_version}"
                    console.print(f"[green]✅ CLAUDE.md deployed successfully![/green]")
                    console.print(f"[dim]🔄 Version: {template_version}[/dim]")
                    console.print(f"[dim]📍 Location: {parent_claude_md}[/dim]")
                    
                    return {
                        "needs_update": False,
                        "parent_exists": True,
                        "parent_path": parent_claude_md,
                        "template_version": template_version,
                        "parent_version": template_version,
                        "status_message": status_message,
                        "auto_updated": True,
                        "backup_path": backup_result
                    }
                else:
                    console.print(f"[red]❌ Auto-deployment failed - manual deployment required[/red]")
                    console.print(f"[yellow]💡 Use 'claude-pm init' to deploy manually[/yellow]")
                    
            except Exception as deploy_error:
                console.print(f"[red]❌ Auto-deployment error: {deploy_error}[/red]")
                console.print(f"[yellow]💡 Use 'claude-pm init' to deploy manually[/yellow]")
            
            return {
                "needs_update": False,
                "parent_exists": False,
                "parent_path": parent_claude_md,
                "template_version": template_version,
                "parent_version": "none",
                "status_message": f"No CLAUDE.md in current directory ({current_dir.name})",
                "auto_updated": False,
                "backup_path": None
            }
        
        # Extract version from parent CLAUDE.md
        parent_version = "unknown"
        try:
            parent_content = parent_claude_md.read_text()
            # Look for version in the deployed template
            # Try FRAMEWORK_VERSION first (deployed version), then CLAUDE_MD_VERSION (for older deployments)
            import re
            version_match = re.search(r'FRAMEWORK_VERSION:\s*(\S+)', parent_content)
            if version_match:
                parent_version = version_match.group(1)
            else:
                # Fallback to CLAUDE_MD_VERSION for compatibility
                version_match = re.search(r'CLAUDE_MD_VERSION:\s*(\S+)', parent_content)
                if version_match:
                    parent_version = version_match.group(1)
                    # Handle old two-part versions by taking just the first part
                    if '-' in parent_version:
                        parent_version = parent_version.split('-')[0]
        except Exception:
            pass
        
        # Compare versions to determine if update is needed
        needs_update = False
        status_message = f"Parent CLAUDE.md version: {parent_version}"
        
        if parent_version == "unknown" or template_version == "unknown":
            # If we can't determine versions, check file modification times
            try:
                parent_mtime = parent_claude_md.stat().st_mtime
                template_mtime = framework_template.stat().st_mtime
                
                if template_mtime > parent_mtime:
                    needs_update = True
                    status_message = "Framework template is newer than parent CLAUDE.md"
                else:
                    status_message = "Parent CLAUDE.md appears current (based on modification time)"
            except Exception:
                status_message = "Cannot determine update status - version information unavailable"
        else:
            # Compare version strings
            if parent_version != template_version:
                needs_update = True
                status_message = f"Update available: {parent_version} → {template_version}"
            else:
                status_message = f"Parent CLAUDE.md is current (version {parent_version})"
        
        # ENHANCED: Automatically perform backup and update if framework is newer
        auto_updated = False
        backup_path = None
        
        if needs_update:
            try:
                console.print(f"[yellow]⚡ Auto-updating CLAUDE.md: {parent_version} → {template_version}[/yellow]")
                
                # Perform automatic backup and update using Parent Directory Manager
                backup_result, update_result = perform_automatic_backup_and_update(
                    current_dir, parent_claude_md, template_version, quiet_mode=True
                )
                
                if backup_result and update_result:
                    auto_updated = True
                    backup_path = backup_result
                    status_message = f"✅ Auto-updated: {parent_version} → {template_version} (backup: {backup_result})"
                    console.print(f"[green]✅ CLAUDE.md updated successfully![/green]")
                    console.print(f"[dim]📁 Backup saved: {backup_result}[/dim]")
                    console.print(f"[dim]🔄 New version: {template_version}[/dim]")
                    needs_update = False  # Update completed
                else:
                    console.print(f"[red]❌ Auto-update failed - manual update required[/red]")
                    
            except Exception as update_error:
                console.print(f"[red]❌ Auto-update error: {update_error}[/red]")
                console.print(f"[yellow]💡 Use 'claude-pm init' to update manually[/yellow]")
        
        return {
            "needs_update": needs_update,
            "parent_exists": True,
            "parent_path": parent_claude_md,
            "template_version": template_version,
            "parent_version": parent_version,
            "status_message": status_message,
            "auto_updated": auto_updated,
            "backup_path": backup_path
        }
        
    except Exception as e:
        return {
            "needs_update": False,
            "parent_exists": False,
            "parent_path": Path.cwd() / "CLAUDE.md",
            "template_version": "unknown",
            "parent_version": "unknown",
            "status_message": f"Error checking parent CLAUDE.md status: {e}",
            "auto_updated": False,
            "backup_path": None
        }


def create_minimal_claude_md():
    """
    Create a minimal CLAUDE.md template from embedded string.
    This is a last resort when no template file can be found.
    """
    # Re-detect framework path for accurate version
    actual_framework_path = detect_framework_path()
    framework_version = get_framework_version(actual_framework_path)
    deployment_date = datetime.now().isoformat()
    deployment_id = int(datetime.now().timestamp())
    
    template = f'''# Claude PM Framework Configuration - Deployment

<!-- 
CLAUDE_MD_VERSION: {framework_version}
FRAMEWORK_VERSION: {framework_version}
DEPLOYMENT_DATE: {deployment_date}
LAST_UPDATED: {deployment_date}
CONTENT_HASH: minimal
-->

## 🤖 AI ASSISTANT ROLE DESIGNATION

**You are operating within a Claude PM Framework deployment**

Your primary role is operating as a multi-agent orchestrator. Your job is to orchestrate projects by:
- **Delegating tasks** to other agents via Task Tool (subprocesses)
- **Providing comprehensive context** to each agent for their specific domain
- **Receiving and integrating results** to inform project progress and next steps
- **Coordinating cross-agent workflows** to achieve project objectives
- **Maintaining project visibility** and strategic oversight throughout execution

### Framework Context
- **Version**: {framework_version}
- **Deployment Date**: {deployment_date}
- **Platform**: {sys.platform}
- **Python Command**: python3
- **Agent Hierarchy**: Three-tier (Project → User → System)
- **Core System**: 🔧 Framework orchestration and agent coordination

---

## A) AGENTS

### Core Agent Types (Mandatory Collaboration)
1. **Documentation Agent** - Project documentation and operational understanding
2. **Ticketing Agent** - Universal ticketing interface and lifecycle management
3. **Version Control Agent** - Git operations and version control
4. **QA Agent** - Quality assurance, testing, and validation
5. **Research Agent** - Investigation, analysis, and information gathering
6. **Ops Agent** - Deployment, operations, and infrastructure management
7. **Security Agent** - Security analysis and vulnerability assessment
8. **Engineer Agent** - Code implementation and development
9. **Data Engineer Agent** - Data store management and AI API integrations

### Task Tool Subprocess Creation Protocol

**Standard Task Tool Orchestration Format:**
```
**[Agent Type] Agent**: [Clear task description with specific deliverables]

TEMPORAL CONTEXT: Today is [current date]. Apply date awareness.

**Task**: [Detailed task breakdown with specific requirements]

**Context**: [Comprehensive filtered context relevant to this agent type]

**Authority**: [Agent writing permissions and scope]
**Expected Results**: [Specific deliverables PM needs back]
```

---

## B) TODO AND TASK TOOLS

### TodoWrite Integration with Task Tool

**Workflow Pattern:**
1. **Create TodoWrite entries** for complex multi-agent tasks
2. **Mark todo as in_progress** when delegating via Task Tool
3. **Update todo status** based on subprocess completion
4. **Mark todo as completed** when agent delivers results

---

## C) CLAUDE-PM INIT

### Core Initialization Commands
```bash
# Basic initialization check
claude-pm init

# Complete setup with directory creation
claude-pm init --setup

# Comprehensive verification of agent hierarchy
claude-pm init --verify
```

---

**Framework Version**: {framework_version}
**Deployment ID**: {deployment_id}
**Last Updated**: {deployment_date}
'''
    
    return template


def ensure_template_in_user_directory():
    """
    Ensure CLAUDE.md template exists in user directory for deployment.
    This is a one-time copy during framework usage.
    """
    user_template_dir = Path.home() / ".claude-pm" / "templates"
    user_template_path = user_template_dir / "CLAUDE.md"
    
    # If template already exists in user directory, we're good
    if user_template_path.exists():
        return True
    
    # Create templates directory if it doesn't exist
    user_template_dir.mkdir(parents=True, exist_ok=True)
    
    # Find source template
    template_locations = [
        framework_path / "framework" / "CLAUDE.md",
        framework_path / "templates" / "CLAUDE.md",
        Path(__file__).parent.parent / "framework" / "CLAUDE.md",
    ]
    
    source_template = None
    for location in template_locations:
        if location.exists():
            source_template = location
            break
    
    if source_template:
        try:
            shutil.copy2(source_template, user_template_path)
            console.print(f"[dim]✅ Template copied to user directory: {user_template_path}[/dim]")
            return True
        except Exception as e:
            console.print(f"[yellow]⚠️ Could not copy template to user directory: {e}[/yellow]")
            return False
    else:
        console.print(f"[yellow]⚠️ Framework template not found in expected locations[/yellow]")
        return False


def perform_automatic_backup_and_update(current_dir, parent_claude_md, template_version, quiet_mode=False):
    """
    Perform automatic backup and update of CLAUDE.md using Parent Directory Manager.
    
    This function integrates with the Parent Directory Manager service to:
    1. Create a timestamped backup of the existing CLAUDE.md file
    2. Deploy the latest framework template to replace the old file
    3. Provide clear feedback about the operation status
    
    Args:
        current_dir: Current working directory Path
        parent_claude_md: Path to existing CLAUDE.md file  
        template_version: Framework template version
        quiet_mode: If True, suppress INFO level logging
        
    Returns:
        Tuple of (backup_path, success) where:
        - backup_path: Path to backup file or None if failed
        - success: True if update succeeded, False otherwise
    """
    # First ensure template exists in user directory
    ensure_template_in_user_directory()
    
    try:
        import asyncio
        
        async def run_backup_and_update():
            try:
                # Try to import the Parent Directory Manager service
                from claude_pm.services.parent_directory_manager import ParentDirectoryManager
            except ImportError as initial_error:
                # If import fails, we're likely in an external project
                # Try to add framework path to sys.path and retry
                if str(framework_path) not in sys.path:
                    sys.path.insert(0, str(framework_path))
                try:
                    from claude_pm.services.parent_directory_manager import ParentDirectoryManager
                except ImportError as e:
                    # If still failing, return special marker for import failure
                    return "IMPORT_FAILED", str(e)
            
            # Initialize the Parent Directory Manager with proper configuration
            manager = ParentDirectoryManager(quiet_mode=quiet_mode)
            await manager._initialize()
            
            backup_path = None
            
            try:
                # Step 1: Create timestamped backup of existing CLAUDE.md
                console.print("[dim]🔄 Creating backup of existing CLAUDE.md...[/dim]")
                parent_dir = current_dir.parent
                backup_path = await manager.backup_parent_directory(parent_dir)
                
                if backup_path:
                    console.print(f"[green]✅ Backup created: {backup_path.name}[/green]")
                else:
                    console.print("[red]⚠️  Backup creation failed - proceeding without backup[/red]")
                
                # Step 2: Install new template from framework using force mode
                console.print("[dim]🔄 Installing updated framework template...[/dim]")
                operation = await manager.install_template_to_parent_directory(
                    target_directory=parent_dir,
                    template_id="claude_md",  # Framework template ID for CLAUDE.md
                    template_variables=None,  # Use default deployment variables
                    force=True  # Force update to override version checking
                )
                
                if operation.success:
                    console.print(f"[green]✅ Template installation successful[/green]")
                    
                    # Log successful automatic update for memory collection - DISABLED
                    # MEMORY SYSTEM DISABLED - Comment out memory collection
                    # if hasattr(manager, 'logger'):
                    #     manager.logger.info(f"Automatic CLAUDE.md update completed: {template_version}")
                    #     manager.logger.info(f"Backup created: {backup_path}")
                    #     manager.logger.info(f"Target directory: {parent_dir}")
                    
                    return backup_path, True
                else:
                    error_msg = operation.error_message or "Unknown error"
                    console.print(f"[red]❌ Template installation failed: {error_msg}[/red]")
                    
                    # Log failure for memory collection - DISABLED
                    # MEMORY SYSTEM DISABLED - Comment out memory collection
                    # if hasattr(manager, 'logger'):
                    #     manager.logger.error(f"Automatic CLAUDE.md update failed: {error_msg}")
                    #     manager.logger.error(f"Template version: {template_version}")
                    #     manager.logger.error(f"Target directory: {current_dir}")
                    
                    return backup_path, False
                    
            except Exception as manager_error:
                error_msg = str(manager_error)
                console.print(f"[red]❌ Parent Directory Manager error: {error_msg}[/red]")
                
                # Log manager error for memory collection - DISABLED
                # MEMORY SYSTEM DISABLED - Comment out memory collection
                # if hasattr(manager, 'logger'):
                #     manager.logger.error(f"Parent Directory Manager error during auto-update: {error_msg}")
                #     manager.logger.error(f"Template version: {template_version}")
                #     manager.logger.error(f"Target directory: {current_dir}")
                
                return backup_path, False
                
            finally:
                # Cleanup manager resources only if it was initialized
                if 'manager' in locals():
                    await manager._cleanup()
        
        # Run the async backup and update operation
        result = asyncio.run(run_backup_and_update())
        
        # If imports failed (indicated by IMPORT_FAILED marker), trigger fallback
        if result and isinstance(result, tuple) and result[0] == "IMPORT_FAILED":
            # Print the import error messages here
            console.print(f"[red]❌ Cannot import Parent Directory Manager: {result[1]}[/red]")
            console.print("[yellow]💡 Framework may not be properly installed[/yellow]")
            raise ImportError(result[1])
        
        return result
        
    except ImportError as import_error:
        console.print(f"[red]❌ Failed to import required modules: {import_error}[/red]")
        console.print("[yellow]💡 Attempting direct CLAUDE.md deployment...[/yellow]")
        
        # Fallback: Try direct file copy if imports fail
        try:
            # First ensure template exists in user directory
            ensure_template_in_user_directory()
            
            # Try multiple locations for the framework template
            framework_template = None
            
            # Re-detect framework path for fallback scenario
            actual_framework_path = detect_framework_path()
            
            template_locations = [
                actual_framework_path / "framework" / "CLAUDE.md",
                framework_path / "framework" / "CLAUDE.md",
                Path.home() / ".claude-pm" / "templates" / "CLAUDE.md",
                Path(__file__).parent.parent / "framework" / "CLAUDE.md",
            ]
            
            # NEW: Also check npm global directory
            try:
                npm_global_result = subprocess.run(
                    ["npm", "root", "-g"], 
                    capture_output=True, 
                    text=True, 
                    timeout=10
                )
                
                if npm_global_result.returncode == 0:
                    npm_global_root = Path(npm_global_result.stdout.strip())
                    npm_template = npm_global_root / "@bobmatnyc" / "claude-multiagent-pm" / "framework" / "CLAUDE.md"
                    template_locations.insert(0, npm_template)
            except (subprocess.TimeoutExpired, FileNotFoundError, Exception):
                pass
            
            for location in template_locations:
                if location.exists():
                    framework_template = location
                    break
            
            if framework_template:
                # Create backup of existing file if it exists
                backup_path = None
                if parent_claude_md.exists():
                    backup_name = f"CLAUDE.md.backup.{datetime.now().strftime('%Y%m%d_%H%M%S')}"
                    backup_path = parent_claude_md.parent / backup_name
                    shutil.copy2(parent_claude_md, backup_path)
                    console.print(f"[green]✅ Backup created: {backup_path.name}[/green]")
                
                # Read template and apply basic substitutions
                template_content = framework_template.read_text()
                
                # Get framework version using the actual framework path
                framework_version = get_framework_version(actual_framework_path)
                
                # Apply basic template substitutions
                deployment_date = datetime.now().isoformat()
                replacements = {
                    '{{CLAUDE_MD_VERSION}}': framework_version,
                    '{{FRAMEWORK_VERSION}}': framework_version,
                    '{{DEPLOYMENT_DATE}}': deployment_date,
                    '{{LAST_UPDATED}}': deployment_date,
                    '{{DEPLOYMENT_ID}}': str(int(datetime.now().timestamp())),
                    '{{PLATFORM_NOTES}}': f'Platform: {sys.platform}'
                }
                
                for placeholder, value in replacements.items():
                    template_content = template_content.replace(placeholder, value)
                
                # Write processed template to parent directory
                parent_claude_md.write_text(template_content)
                console.print(f"[green]✅ CLAUDE.md deployed directly with template substitutions[/green]")
                return backup_path, True
            else:
                # Last resort: create minimal CLAUDE.md from embedded template
                console.print(f"[yellow]⚠️ No template file found - creating minimal CLAUDE.md[/yellow]")
                try:
                    minimal_template = create_minimal_claude_md()
                    parent_claude_md.write_text(minimal_template)
                    console.print(f"[green]✅ Minimal CLAUDE.md created successfully[/green]")
                    return None, True
                except Exception as minimal_error:
                    console.print(f"[red]❌ Failed to create minimal template: {minimal_error}[/red]")
                    return None, False
                
        except Exception as copy_error:
            console.print(f"[red]❌ Direct deployment failed: {copy_error}[/red]")
            return None, False
        
    except Exception as e:
        console.print(f"[red]❌ Backup and update operation failed: {e}[/red]")
        return None, False


def display_parent_claude_md_notification(check_result):
    """
    Display notification about parent CLAUDE.md status with actionable guidance.
    Enhanced to handle automatic updates and hierarchy detection.
    
    Args:
        check_result: Dict from check_parent_claude_md_status()
    """
    # Check if CLAUDE.md exists in hierarchy
    if "hierarchy_claude_md" in check_result and check_result["hierarchy_claude_md"]:
        console.print(f"[green]📄 Using CLAUDE.md from: {check_result['hierarchy_claude_md']}[/green]")
        return
    
    if not check_result["parent_exists"]:
        # No parent CLAUDE.md - this is normal for many directories
        console.print(f"[dim]📄 Parent CLAUDE.md: {check_result['status_message']}[/dim]")
        return
    
    # Check if automatic update was performed
    if check_result.get("auto_updated", False):
        # Automatic update was successful
        console.print("")
        console.print("[bold green]📄 CLAUDE.md Auto-Update Complete[/bold green]")
        console.print("─" * 50)
        console.print(f"📍 Location: {check_result['parent_path']}")
        console.print(f"✅ Status: {check_result['status_message']}")
        if check_result.get("backup_path"):
            console.print(f"🛡️  Backup: {check_result['backup_path']}")
        console.print("")
        console.print("[dim]🎉 Your CLAUDE.md file has been automatically updated with the latest[/dim]")
        console.print("[dim]   framework features, agent types, and configuration options.[/dim]")
        console.print("")
        return
    
    if check_result["needs_update"]:
        # Parent file needs updating (automatic update failed or not attempted)
        console.print("")
        console.print("[bold yellow]📄 CLAUDE.md Update Available[/bold yellow]")
        console.print("─" * 50)
        console.print(f"📍 Location: {check_result['parent_path']}")
        console.print(f"📊 Status: {check_result['status_message']}")
        console.print("")
        console.print("[bold]💡 Manual update options:[/bold]")
        console.print("   • claude-pm init          (recommended - updates all framework files)")
        console.print("   • claude-pm setup         (alternative update method)")
        console.print("   • claude-pm deploy        (force deployment)")
        console.print("")
        console.print("[dim]💬 This update will bring your CLAUDE.md file up to date with the latest[/dim]")
        console.print("[dim]   framework features, agent types, and configuration options.[/dim]")
        console.print("")
    else:
        # Parent file is current
        console.print(f"[green]📄 Parent CLAUDE.md: {check_result['status_message']}[/green]")


def attempt_auto_installation():
    """Attempt to automatically install the framework if postinstall didn't run."""
    console.print("[yellow]⚠️  Framework not detected - attempting auto-installation...[/yellow]")
    console.print("[dim]🔍 Scanning for installation scripts...[/dim]")
    
    # Check if we can find the postinstall script
    postinstall_paths = [
        framework_path / "install" / "postinstall.js",
        framework_path / "install" / "postinstall-enhanced.js"
    ]
    
    for postinstall_path in postinstall_paths:
        if postinstall_path.exists():
            console.print(f"[dim]✅ Found postinstall script: {postinstall_path}[/dim]")
            console.print("[dim]🚀 Executing enhanced postinstall script...[/dim]")
            
            try:
                # Run the postinstall script
                result = subprocess.run(
                    ["node", str(postinstall_path)], 
                    cwd=str(framework_path),
                    capture_output=True,
                    text=True,
                    timeout=120  # 2 minutes timeout
                )
                
                if result.returncode == 0:
                    console.print("[green]✅ Auto-installation completed successfully![/green]")
                    console.print("[dim]📋 Installation output:[/dim]")
                    if result.stdout:
                        # Show last few lines of output
                        lines = result.stdout.strip().split('\n')[-5:]
                        for line in lines:
                            console.print(f"[dim]   {line}[/dim]")
                    return True
                else:
                    console.print(f"[red]❌ Auto-installation failed[/red]")
                    if result.stderr:
                        console.print(f"[red]   Error: {result.stderr}[/red]")
                    
            except subprocess.TimeoutExpired:
                console.print("[red]❌ Auto-installation timed out[/red]")
            except Exception as e:
                console.print(f"[red]❌ Auto-installation error: {e}[/red]")
                
            break
    
    # Alternative: Try to run npm install in the framework directory
    console.print("[yellow]🔄 Attempting alternative installation via npm...[/yellow]")
    try:
        result = subprocess.run(
            ["npm", "run", "install:unified"],
            cwd=str(framework_path),
            capture_output=True,
            text=True,
            timeout=120
        )
        
        if result.returncode == 0:
            console.print("[green]✅ Alternative installation completed successfully![/green]")
            return True
        else:
            console.print(f"[red]❌ Alternative installation failed[/red]")
            if result.stderr:
                console.print(f"[red]   Error: {result.stderr}[/red]")
            
    except Exception as e:
        console.print(f"[red]❌ Alternative installation error: {e}[/red]")
    
    return False


def validate_claude_cli():
    """Validate that Claude CLI is available."""
    try:
        result = subprocess.run(
            ["claude", "--version"], 
            capture_output=True, 
            text=True, 
            timeout=5
        )
        if result.returncode == 0:
            return {
                "valid": True,
                "version": result.stdout.strip(),
                "command": ["claude"]
            }
    except (subprocess.TimeoutExpired, FileNotFoundError):
        pass
    
    return {
        "valid": False,
        "error": "Claude CLI not found or not accessible",
        "command": ["claude"]
    }


def show_help():
    """Display help information."""
    package_version = get_framework_version()
    
    # Get framework/CLAUDE.md version
    framework_version_file = framework_path / "framework" / "VERSION"
    framework_version = "unknown"
    if framework_version_file.exists():
        try:
            framework_version = framework_version_file.read_text().strip()
        except:
            pass
    
    console.print(f"""
[bold blue]Claude Multi-Agent PM Framework[/bold blue]
[dim]Package: v{package_version} | Script: {SCRIPT_VERSION} | Framework: {framework_version}[/dim]
Pure Python CLI for Claude-powered project management and task orchestration

[bold]🚀 USAGE:[/bold]
  claude-pm [command] [options]

[bold]📋 COMMANDS:[/bold]
  --version               Show version information
  --help, -h              Show this help message
  --system-info           Display comprehensive system information
  --deployment-info       Show deployment detection results
  init                    Initialize framework (manual init command)
  --cleanup               Comprehensive framework removal tool
  
[bold]🚨 ENHANCED FLAGS (Pure Python Implementation):[/bold]
  --safe                  Enable safe mode with confirmations and backups
  --upgrade [VERSION]     Upgrade to latest or specified version
  --rollback VERSION      Rollback to specific version
  --dry-run              Show what would be done without executing
  --test-mode            Enable test mode with prompt logging to .claude-pm/logs/prompts/

[bold]⚡ YOLO Mode (Default):[/bold]
  claude-pm               Launch Claude CLI directly (YOLO mode - fast startup)

[bold]🛠️ INITIALIZATION:[/bold]
  claude-pm init                   🚀 Smart initialization - just works! (auto-detects and runs post-install if needed)
  claude-pm init --force           Force re-initialization (runs post-install even if already set up)
  claude-pm init --skip-postinstall Skip post-install setup (for advanced users)
  claude-pm init --validate        Validate installation without making changes

[bold]🧹 CLEANUP & REMOVAL:[/bold]
  claude-pm --cleanup              🗑️  Interactive comprehensive cleanup (safest option)
  claude-pm --cleanup --auto       Automatic cleanup (keeps user data)
  claude-pm --cleanup --full       Complete removal including user data (with backup)
  npm run cleanup                  Alternative cleanup via npm script
  npm run uninstall:complete       Full interactive uninstall process

[bold]🚨 TROUBLESHOOTING:[/bold]
  • Setup Issues: claude-pm init (will auto-fix missing components)
  • Environment Issues: claude-pm --system-info
  • Deployment Problems: claude-pm --deployment-info

[bold]📖 DOCUMENTATION:[/bold]
  • GitHub: https://github.com/bobmatnyc/claude-multiagent-pm

---
Made with ❤️  for AI-powered development workflows (Pure Python Edition)
""")


def display_system_info():
    """Display system information."""
    deployment_info = detect_deployment_type()
    framework_version = get_framework_version()
    script_path = get_script_path()
    
    console.print("[bold]🖥️  Claude Multi-Agent PM Framework System Information[/bold]")
    console.print("═" * 60)
    console.print(f"📦 Framework Version: v{framework_version}")
    console.print(f"🔧 Script Version: {SCRIPT_VERSION}")
    console.print(f"📍 Script Path: {script_path}")
    console.print(f"🗂️  Deployment Type: {deployment_info['type']}")
    console.print(f"📁 Framework Path: {deployment_info['framework_path']}")
    console.print(f"🔧 Platform: {sys.platform}")
    console.print(f"🐍 Python: {sys.version.split()[0]}")
    console.print("")


def display_deployment_info():
    """Display deployment detection results."""
    deployment_info = detect_deployment_type()
    console.print("\n[bold]🔍 Deployment Detection Results:[/bold]")
    console.print("═" * 60)
    import json
    console.print(json.dumps(deployment_info, indent=2, default=str))


def display_comprehensive_status():
    """Display comprehensive framework status checks."""
    console.print("[bold blue]🔍 Claude PM Framework Status Validation[/bold blue]")
    console.print("═" * 60)
    
    # Project version
    project_version = get_framework_version()
    console.print(f"📦 Project Version: [green]v{project_version}[/green]")
    console.print(f"🔧 Script Version: [green]{SCRIPT_VERSION}[/green]")
    
    # Script path - show which claude-pm executable is being used
    script_path = get_script_path()
    console.print(f"📍 Script Path: [cyan]{script_path}[/cyan]")
    
    # Framework/CLAUDE.md version (serial number from framework/VERSION)
    framework_version_file = framework_path / "framework" / "VERSION"
    if framework_version_file.exists():
        try:
            framework_version = framework_version_file.read_text().strip()
            console.print(f"📋 Framework/CLAUDE.md Version: [green]{framework_version}[/green]")
        except:
            console.print("📋 Framework/CLAUDE.md Version: [yellow]read error[/yellow]")
    else:
        console.print("📋 Framework/CLAUDE.md Version: [yellow]not found[/yellow]")
    
    # Memory system status with mem0AI version and memory count
    memory_status = check_memory_status()
    memory_color = "green" if memory_status["healthy"] else "yellow" if memory_status["partial"] else "red"
    # console.print(f"🧠 Memory System: [{memory_color}]{memory_status['status']}[/{memory_color}]")
    
    # Framework deployment status
    deployment_valid = validate_framework_deployment()
    deploy_color = "green" if deployment_valid else "red"
    deploy_status = "✅ Deployed" if deployment_valid else "❌ Not Deployed"
    console.print(f"🚀 Framework Deployment: [{deploy_color}]{deploy_status}[/{deploy_color}]")
    
    # Claude CLI status
    claude_validation = validate_claude_cli()
    claude_color = "green" if claude_validation["valid"] else "red"
    claude_status = f"✅ v{claude_validation.get('version', 'unknown')}" if claude_validation["valid"] else "❌ Not Found"
    console.print(f"🤖 Claude CLI: [{claude_color}]{claude_status}[/{claude_color}]")
    
    console.print("═" * 60)
    
    # Check parent directory CLAUDE.md status
    parent_check = check_parent_claude_md_status()
    display_parent_claude_md_notification(parent_check)


def check_memory_status():
    """Check memory system status - DISABLED to fix installation issues."""
    # MEMORY SYSTEM DISABLED - Causes installation failures
    # TODO: Re-enable after memory system is fixed and working properly
    
    # Simply return disabled status to avoid import errors and installation problems
    return {
        "healthy": False,
        "partial": False,
        "status": "🚫 Disabled (fixes installation issues)"
    }
    
    # Original memory checking code commented out to prevent install problems:
    # try:
    #     # Check for mem0AI installation and version
    #     mem0_version = "not installed"
    #     memory_count = 0
    #     
    #     # Get memory system serial version from VERSION file
    #     memory_system_version = "unknown"
    #     try:
    #         memory_version_file = framework_path / "claude_pm" / "services" / "memory" / "VERSION"
    #         if memory_version_file.exists():
    #             memory_system_version = memory_version_file.read_text().strip()
    #     except:
    #         pass
    #     
    #     # Check if mem0AI is installed via pip
    #     try:
    #         import subprocess
    #         # Use python -m pip to avoid PATH issues
    #         result = subprocess.run([sys.executable, "-m", "pip", "show", "mem0ai"], capture_output=True, text=True, timeout=5)
    #         if result.returncode == 0:
    #             import re
    #             version_match = re.search(r'Version:\s*(\S+)', result.stdout)
    #             if version_match:
    #                 mem0_version = version_match.group(1)
    #     except:
    #         # Try alternative package names
    #         try:
    #             result = subprocess.run([sys.executable, "-m", "pip", "show", "mem0"], capture_output=True, text=True, timeout=5)
    #             if result.returncode == 0:
    #                 import re
    #                 version_match = re.search(r'Version:\s*(\S+)', result.stdout)
    #                 if version_match:
    #                     mem0_version = version_match.group(1)
    #         except:
    #             pass
    #     
    #     # Check for memory storage locations and count memories
    #     memory_locations = [
    #         Path.home() / ".mem0",  # Default mem0 location
    #         Path.home() / ".claude-pm" / "memory",  # Framework memory location
    #         framework_path / "memory",  # Local memory storage
    #         framework_path / "logs" / "memory"  # Memory logs
    #     ]
    #     
    #     for loc in memory_locations:
    #         if loc.exists() and loc.is_dir():
    #             try:
    #                 # Count actual memory files (json, db, etc.)
    #                 memory_files = list(loc.glob("**/*.json")) + list(loc.glob("**/*.db")) + list(loc.glob("**/*.sqlite"))
    #                 memory_count += len(memory_files)
    #                 
    #                 # Also check for any files that might be memories
    #                 if memory_count == 0:
    #                     all_files = [f for f in loc.glob("**/*") if f.is_file()]
    #                     memory_count += len(all_files)
    #             except:
    #                 pass
    #     
    #     # Check if memory optimization files exist  
    #     memory_opt_files = [
    #         framework_path / "scripts" / "memory-optimization.js",
    #         framework_path / "scripts" / "memory-monitor.js",
    #         framework_path / "scripts" / "memory-dashboard.js"
    #     ]
    #     
    #     optimization_exists = any(f.exists() for f in memory_opt_files)
    #     
    #     # Check for mem0 service
    #     mem0_service_running = False
    #     try:
    #         # Check if mem0 service script exists
    #         mem0_service_script = framework_path / "scripts" / "mem0_service.py"
    #         if mem0_service_script.exists():
    #             mem0_service_running = True
    #     except:
    #         pass
    #     
    #     # Determine status based on findings
    #     if mem0_version != "not installed" and memory_count > 0:
    #         return {
    #             "healthy": True, 
    #             "partial": False,
    #             "status": f"✅ mem0AI v{mem0_version} | Memory v{memory_system_version} ({memory_count} memories)"
    #         }
    #     elif mem0_version != "not installed" and mem0_service_running:
    #         return {
    #             "healthy": True,
    #             "partial": False, 
    #             "status": f"✅ mem0AI v{mem0_version} | Memory v{memory_system_version} (service ready)"
    #         }
    #     elif mem0_version != "not installed":
    #         return {
    #             "healthy": False,
    #             "partial": True,
    #             "status": f"⚠️ mem0AI v{mem0_version} | Memory v{memory_system_version} (no memories)"
    #         }
    #     elif optimization_exists:
    #         return {
    #             "healthy": False,
    #             "partial": True, 
    #             "status": f"⚠️ Optimization only | Memory v{memory_system_version} (mem0AI: {mem0_version})"
    #         }
    #     else:
    #         return {
    #             "healthy": False,
    #             "partial": False,
    #             "status": f"❌ Not configured | Memory v{memory_system_version}"
    #         }
    # except Exception as e:
    #     # Try to get memory system version even if there's an error
    #     memory_system_version = "unknown"
    #     try:
    #         memory_version_file = framework_path / "claude_pm" / "services" / "memory" / "VERSION"
    #         if memory_version_file.exists():
    #             memory_system_version = memory_version_file.read_text().strip()
    #     except:
    #         pass
    #     
    #     return {
    #         "healthy": False,
    #         "partial": False, 
    #         "status": f"❌ Error | Memory v{memory_system_version}: {str(e)[:20]}..."
    #     }


def ensure_prompts_directory():
    """
    Ensure the .claude-pm/logs/prompts directory exists for test mode.
    This is called when --test-mode is enabled.
    
    Returns:
        Path: The path to the prompts directory
    """
    try:
        current_dir = Path.cwd()
        prompts_dir = current_dir / ".claude-pm" / "logs" / "prompts"
        prompts_dir.mkdir(parents=True, exist_ok=True)
        return prompts_dir
    except Exception as e:
        # Silently fail - don't interrupt the user's workflow
        return None


def ensure_project_initialized():
    """
    Ensure the project has a .claude-pm directory with basic structure.
    This runs automatically before any command execution to prevent errors.
    
    Returns:
        bool: True if directory was created, False if already existed
    """
    try:
        # Check if .claude-pm directory exists in current project
        current_dir = Path.cwd()
        claude_pm_dir = current_dir / ".claude-pm"
        
        if not claude_pm_dir.exists():
            # Create the basic structure silently
            dirs_to_create = [
                claude_pm_dir / "logs",
                claude_pm_dir / "logs" / "prompts",  # Add prompts subdirectory
                claude_pm_dir / "agents",
                claude_pm_dir / "agents" / "project-specific",
                claude_pm_dir / "config",
                claude_pm_dir / "templates",
                claude_pm_dir / "memory",
                claude_pm_dir / "framework_backups",
            ]
            
            for dir_path in dirs_to_create:
                dir_path.mkdir(parents=True, exist_ok=True)
            
            # Create a basic project config
            project_config = claude_pm_dir / "config" / "project.json"
            if not project_config.exists():
                import json
                config_data = {
                    "project_name": current_dir.name,
                    "created": datetime.now().isoformat(),
                    "framework_version": get_framework_version(),
                    "auto_initialized": True
                }
                with open(project_config, 'w') as f:
                    json.dump(config_data, f, indent=2)
            
            # Try to log if logging is available
            try:
                import logging
                logger = logging.getLogger("claude_pm")
                logger.debug(f"Auto-initialized .claude-pm directory in {current_dir}")
            except:
                # Logging not available, continue silently
                pass
            
            return True
        
        return False
        
    except Exception as e:
        # Silently fail - don't interrupt the user's workflow
        try:
            import logging
            logger = logging.getLogger("claude_pm")
            logger.debug(f"Failed to auto-initialize .claude-pm directory: {e}")
        except:
            # Even logging failed, just continue
            pass
        return False


def launch_claude_cli_yolo(test_mode=False):
    """Launch Claude CLI in proper YOLO mode with essential flags and AbortSignal configuration."""
    validation = validate_claude_cli()
    
    if not validation["valid"]:
        console.print("[red]❌ Claude CLI validation failed[/red]")
        console.print(f"   Error: {validation['error']}")
        console.print("\n[bold]🔧 Solutions:[/bold]")
        console.print("   • Install Claude CLI: https://claude.ai/download")
        console.print("   • Add Claude CLI to your PATH")
        console.print("   • Restart your terminal")
        sys.exit(1)
    
    # Handle test mode setup
    if test_mode:
        prompts_dir = ensure_prompts_directory()
        if prompts_dir:
            console.print(f"[dim]Test mode enabled - prompts will be logged to: {prompts_dir}[/dim]")
            # Set environment variable for Claude CLI to enable prompt logging
            os.environ["CLAUDE_PM_TEST_MODE"] = "true"
            os.environ["CLAUDE_PM_PROMPTS_DIR"] = str(prompts_dir)
        else:
            console.print("[yellow]⚠️ Could not create prompts directory for test mode[/yellow]")
    
    # Launch Claude CLI with essential YOLO mode flags using wrapper
    try:
        import shutil
        claude_path = shutil.which("claude")
        if not claude_path:
            console.print("[red]❌ Claude CLI not found in PATH[/red]")
            sys.exit(1)
        
        # Check if Node.js wrapper exists for AbortSignal MaxListeners configuration
        # This wrapper resolves "MaxListeners exceeded" warnings from multi-agent coordination
        wrapper_path = framework_path / "scripts" / "claude-wrapper.js"
        
        if wrapper_path.exists():
            # Use Node.js wrapper to configure AbortSignal MaxListeners to 25
            # This prevents "11 abort listeners added to [AbortSignal]. MaxListeners is 10" warnings
            console.print("[dim]Using enhanced Claude wrapper for multi-agent coordination[/dim]")
            
            # Essential YOLO mode arguments for wrapper
            wrapper_args = [
                "node", str(wrapper_path),
                "--model", "opus", 
                "--dangerously-skip-permissions"
            ]
            
            # Add test mode flag if enabled
            if test_mode:
                wrapper_args.extend(["--test-mode", "--verbose"])
            
            console.print(f"[dim]Launching Claude with wrapper: {' '.join(wrapper_args[2:])}[/dim]")
            
            # Use os.execvp with the wrapper
            os.execvp("node", wrapper_args)
        else:
            # Fallback to direct Claude launch
            console.print("[dim]Wrapper not found, using direct Claude launch[/dim]")
            
            # Essential YOLO mode arguments
            claude_args = [
                "claude",
                "--model", "opus", 
                "--dangerously-skip-permissions"
            ]
            
            # Add test mode flag if enabled (verbose flag for prompt logging)
            if test_mode:
                claude_args.append("--verbose")
            
            console.print(f"[dim]Launching Claude with: {' '.join(claude_args[1:])}[/dim]")
            
            # Use os.execvp for proper terminal handling in YOLO mode
            os.execvp("claude", claude_args)
        
    except Exception as e:
        console.print(f"[red]❌ Failed to launch Claude CLI: {e}[/red]")
        sys.exit(1)


def launch_claude_cli_with_args(args, test_mode=False):
    """Launch Claude CLI with pass-through arguments and AbortSignal configuration."""
    validation = validate_claude_cli()
    
    if not validation["valid"]:
        console.print("[red]❌ Claude CLI validation failed[/red]")
        console.print(f"   Error: {validation['error']}")
        sys.exit(1)
    
    # Handle test mode setup
    if test_mode:
        prompts_dir = ensure_prompts_directory()
        if prompts_dir:
            console.print(f"[dim]Test mode enabled - prompts will be logged to: {prompts_dir}[/dim]")
            # Set environment variable for Claude CLI to enable prompt logging
            os.environ["CLAUDE_PM_TEST_MODE"] = "true"
            os.environ["CLAUDE_PM_PROMPTS_DIR"] = str(prompts_dir)
        else:
            console.print("[yellow]⚠️ Could not create prompts directory for test mode[/yellow]")
    
    # Launch Claude CLI with pass-through args plus essential flags using wrapper
    try:
        import shutil
        claude_path = shutil.which("claude")
        if not claude_path:
            console.print("[red]❌ Claude CLI not found in PATH[/red]")
            sys.exit(1)
        
        # Check if Node.js wrapper exists for AbortSignal MaxListeners configuration
        # This wrapper resolves "MaxListeners exceeded" warnings from multi-agent coordination
        wrapper_path = framework_path / "scripts" / "claude-wrapper.js"
        
        if wrapper_path.exists():
            # Use Node.js wrapper to configure AbortSignal MaxListeners to 25
            # This prevents "11 abort listeners added to [AbortSignal]. MaxListeners is 10" warnings
            console.print("[dim]Using enhanced Claude wrapper for multi-agent coordination[/dim]")
            
            # Build command with essential flags + pass-through args for wrapper
            wrapper_args = [
                "node", str(wrapper_path),
                "--model", "opus",
                "--dangerously-skip-permissions"
            ]
            
            # Add test mode flag if enabled
            if test_mode:
                wrapper_args.extend(["--test-mode", "--verbose"])
                
            wrapper_args.extend(args)
            
            console.print(f"[dim]Launching Claude with wrapper: {' '.join(wrapper_args[2:])}[/dim]")
            
            # Use os.execvp with the wrapper
            os.execvp("node", wrapper_args)
        else:
            # Fallback to direct Claude launch
            console.print("[dim]Wrapper not found, using direct Claude launch[/dim]")
            
            # Build command with essential flags + pass-through args
            claude_args = [
                "claude",
                "--model", "opus",
                "--dangerously-skip-permissions"
            ]
            
            # Add test mode flag if enabled (verbose flag for prompt logging)
            if test_mode:
                claude_args.append("--verbose")
                
            claude_args.extend(args)
            
            console.print(f"[dim]Launching Claude with: {' '.join(claude_args[1:])}[/dim]")
            
            # Use os.execvp for proper terminal handling
            os.execvp("claude", claude_args)
        
    except Exception as e:
        console.print(f"[red]❌ Failed to launch Claude CLI: {e}[/red]")
        sys.exit(1)


def launch_claude_cli():
    """Launch Claude CLI directly (legacy method) with AbortSignal configuration."""
    validation = validate_claude_cli()
    
    if not validation["valid"]:
        console.print("[red]❌ Claude CLI validation failed[/red]")
        console.print(f"   Error: {validation['error']}")
        console.print("\n[bold]🔧 Solutions:[/bold]")
        console.print("   • Install Claude CLI: https://claude.ai/download")
        console.print("   • Add Claude CLI to your PATH")
        console.print("   • Restart your terminal")
        sys.exit(1)
    
    # Launch Claude CLI with wrapper support
    try:
        # Check if Node.js wrapper exists for AbortSignal MaxListeners configuration
        # This wrapper resolves "MaxListeners exceeded" warnings from multi-agent coordination
        wrapper_path = framework_path / "scripts" / "claude-wrapper.js"
        
        if wrapper_path.exists():
            # Use Node.js wrapper to configure AbortSignal MaxListeners to 25
            # This prevents "11 abort listeners added to [AbortSignal]. MaxListeners is 10" warnings
            console.print("[dim]Using enhanced Claude wrapper for multi-agent coordination[/dim]")
            
            # Launch with wrapper (no additional args for legacy mode)
            wrapper_args = ["node", str(wrapper_path)]
            
            # Use os.execvp with the wrapper
            os.execvp("node", wrapper_args)
        else:
            # Fallback to direct Claude launch
            console.print("[dim]Wrapper not found, using direct Claude launch[/dim]")
            os.execvp("claude", ["claude"])
    except FileNotFoundError:
        console.print("[red]❌ Failed to launch Claude CLI[/red]")
        sys.exit(1)


def handle_enhanced_flags():
    """Handle enhanced flags using pure Python implementation."""
    # Import the CLI flags module
    try:
        from claude_pm.cli_flags import cli_flags
        
        # Remove the script name from args and pass to Click
        sys.argv[0] = "claude-pm"
        cli_flags()
        
    except ImportError as e:
        console.print(f"[red]❌ Failed to import CLI flags module: {e}[/red]")
        console.print("Make sure the Claude PM Framework is properly installed.")
        sys.exit(1)


def attempt_python_package_installation():
    """Attempt to install the Python package if it's missing."""
    console.print("[yellow]⚠️  Python package not found - attempting installation...[/yellow]")
    
    try:
        # Find available Python command
        python_commands = ['python3', 'python']
        python_cmd = None
        
        for cmd in python_commands:
            try:
                result = subprocess.run([cmd, '--version'], capture_output=True, text=True, timeout=5)
                if result.returncode == 0 and 'Python 3.' in result.stdout:
                    python_cmd = cmd
                    break
            except (subprocess.TimeoutExpired, FileNotFoundError):
                continue
        
        if not python_cmd:
            console.print("[red]❌ Python 3.8+ not found[/red]")
            return False
        
        console.print(f"[dim]Using Python command: {python_cmd}[/dim]")
        
        # Try to install the package in editable mode
        try:
            console.print("[dim]Installing Python package in editable mode...[/dim]")
            result = subprocess.run([
                python_cmd, '-m', 'pip', 'install', '--user', '-e', '.'
            ], cwd=str(framework_path), capture_output=True, text=True, timeout=60)
            
            if result.returncode == 0:
                console.print("[green]✅ Python package installed successfully![/green]")
                return True
            else:
                # Try with --break-system-packages for externally managed environments
                if 'externally-managed-environment' in result.stderr or 'externally managed' in result.stderr:
                    console.print("[dim]Retrying with --break-system-packages...[/dim]")
                    result = subprocess.run([
                        python_cmd, '-m', 'pip', 'install', '--user', '--break-system-packages', '-e', '.'
                    ], cwd=str(framework_path), capture_output=True, text=True, timeout=60)
                    
                    if result.returncode == 0:
                        console.print("[green]✅ Python package installed successfully![/green]")
                        return True
                
                console.print(f"[red]❌ Package installation failed: {result.stderr}[/red]")
                return False
                
        except subprocess.TimeoutExpired:
            console.print("[red]❌ Package installation timed out[/red]")
            return False
        except Exception as e:
            console.print(f"[red]❌ Package installation error: {e}[/red]")
            return False
            
    except Exception as e:
        console.print(f"[red]❌ Python package installation failed: {e}[/red]")
        return False

def handle_init_command(args):
    """Handle the init command with intelligent auto-initialization."""
    # Parse command flags
    force = "--force" in args
    skip_postinstall = "--skip-postinstall" in args
    validate_only = "--validate" in args
    
    # Configure logging based on force flag
    if force:
        # Suppress INFO logging when --force is used
        import logging
        import os
        # Set environment variable for services to respect quiet mode
        os.environ['CLAUDE_PM_QUIET_MODE'] = 'true'
        
        # Configure logging to suppress INFO messages
        logging.basicConfig(level=logging.ERROR)
        
        # Suppress Rich console output for quiet mode
        console.print = lambda *args, **kwargs: None
        
        # Use quiet logging module
        sys.path.insert(0, str(framework_path))
        try:
            from claude_pm.core.quiet_logging import setup_quiet_logging
            setup_quiet_logging()
        except ImportError:
            # Fallback if quiet_logging module not available
            pass
    else:
        console.print("[bold blue]🛠️  Claude PM Framework Initialization[/bold blue]")
        console.print("[dim]Intelligent initialization - detecting setup requirements...[/dim]")
    
    try:
        # Basic framework initialization without agent system
        import asyncio
        import json
        
        async def run_basic_init():
            if not force:  # Only show verbose output if not in force mode
                console.print("\n[bold]🔧 Running basic framework initialization...[/bold]")
            
            # Create basic framework directories
            framework_path = Path.home() / ".claude-pm"
            framework_path.mkdir(parents=True, exist_ok=True)
            
            # Create basic config
            config_path = framework_path / "config.json"
            if not config_path.exists() or force:
                config_data = {
                    "version": get_framework_version(),
                    "installationType": "python",
                    "installationComplete": True,
                    "timestamp": datetime.now().isoformat(),
                    "framework_path": str(framework_path),
                    "agent_system": "disabled"  # Agent system removed
                }
                
                with open(config_path, 'w') as f:
                    json.dump(config_data, f, indent=2)
                
                if not force:  # Only show verbose output if not in force mode
                    console.print(f"✅ Created configuration: {config_path}")
            
            # Create basic directory structure
            dirs_to_create = [
                framework_path / "logs",
                framework_path / "templates",
                framework_path / "memory",
            ]
            
            for dir_path in dirs_to_create:
                dir_path.mkdir(parents=True, exist_ok=True)
                if not force:  # Only show verbose output if not in force mode
                    console.print(f"✅ Created directory: {dir_path}")
            
            # Deploy CLAUDE.md to parent directory with force flag
            if force:
                try:
                    from claude_pm.services.parent_directory_manager import ParentDirectoryManager
                    
                    # Initialize Parent Directory Manager with quiet mode if force is used
                    manager = ParentDirectoryManager(quiet_mode=force)
                    await manager._initialize()
                    
                    # Get current working directory and parent directory
                    current_dir = Path.cwd()
                    parent_dir = current_dir.parent
                    
                    # Deploy CLAUDE.md with force flag
                    operation = await manager.install_template_to_parent_directory(
                        target_directory=parent_dir,
                        template_id="claude_md",
                        template_variables=None,  # Use defaults
                        force=True  # Force deployment when --force flag is used
                    )
                    
                    # Only show output if not in force mode or if there's an error
                    if not operation.success:
                        console.print(f"❌ CLAUDE.md deployment failed: {operation.error_message}")
                    
                    if 'manager' in locals():
                        await manager._cleanup()
                    
                except Exception as deploy_error:
                    # Always show deployment errors
                    console.print(f"❌ CLAUDE.md deployment error: {deploy_error}")
                    # Continue with initialization even if deployment fails
            
            return True
        
        # Run the basic initialization
        if force:
            # Use quiet logging context for all operations
            from claude_pm.core.quiet_logging import quiet_logging
            with quiet_logging():
                success = asyncio.run(run_basic_init())
        else:
            success = asyncio.run(run_basic_init())
        
        if success:
            # Load framework into Claude Code after successful deployment (when --force is used)
            if force:
                try:
                    from claude_pm.services.claude_code_integration import load_framework_into_claude_code, create_framework_loading_summary
                    
                    # Load framework with retry logic (pass quiet_mode when force is used)
                    framework_loaded = asyncio.run(load_framework_into_claude_code(quiet_mode=force))
                    
                    if framework_loaded:
                        if not force:  # Only show verbose output if not in force mode
                            console.print("[green]✅ Framework successfully loaded into Claude Code![/green]")
                            console.print("[dim]🎯 Framework is now active and ready for use[/dim]")
                    else:
                        if not force:  # Only show verbose output if not in force mode
                            console.print("[yellow]⚠️ Framework initialization completed but Claude Code loading failed[/yellow]")
                            console.print("[dim]💡 You can still use claude-pm commands, but framework may not be fully active[/dim]")
                            
                except Exception as loading_error:
                    if not force:  # Only show verbose output if not in force mode
                        console.print(f"[red]❌ Framework loading error: {loading_error}[/red]")
                        console.print("[dim]💡 Framework initialization completed but loading failed[/dim]")
            
            if not force:  # Only show verbose output if not in force mode
                console.print("[green]\n✅ Framework initialization completed successfully![/green]")
                console.print("[dim]🚀 Claude PM Framework is ready to use[/dim]")
                console.print("[dim]📖 Use Claude Code Task Tool for agent functionality[/dim]")
                console.print("[dim]   Try: claude-pm --help[/dim]")
            sys.exit(0)
        else:
            if not force:  # Only show verbose output if not in force mode
                console.print("[red]\n❌ Framework initialization failed![/red]")
                console.print("[dim]🔧 Check the output above for errors[/dim]")
            sys.exit(1)
            
    except ImportError as e:
        if not force:  # Only show verbose output if not in force mode
            console.print(f"[red]❌ Failed to import required modules: {e}[/red]")
            console.print("[dim]This usually indicates the Python package is not installed[/dim]")
        
        # Attempt automatic Python package installation
        if attempt_python_package_installation():
            if not force:  # Only show verbose output if not in force mode
                console.print("[green]✅ Package installed! Please run the command again.[/green]")
            sys.exit(0)
        else:
            if not force:  # Only show verbose output if not in force mode
                console.print("[red]❌ Automatic installation failed[/red]")
                console.print("\n[bold]🔧 Manual installation required:[/bold]")
                console.print("   1. Navigate to the framework directory:")
                console.print(f"      cd {framework_path}")
                console.print("   2. Install the Python package:")
                console.print("      pip install -e .")
                console.print("   3. Or run npm installation:")
                console.print("      npm run install:dependencies")
                console.print("   4. Then retry the command")
            sys.exit(1)
    except Exception as e:
        if not force:  # Only show verbose output if not in force mode
            console.print(f"[red]❌ Initialization error: {e}[/red]")
        sys.exit(1)


def handle_cleanup_command(args):
    """Handle the --cleanup command with self-removal capabilities."""
    console.print("[bold red]🧹 Claude PM Framework Self-Removal Tool[/bold red]")
    console.print("[dim]Comprehensive cleanup system with user data handling...[/dim]")
    
    # Parse cleanup flags
    interactive = "--interactive" in args or "--full" in args
    automatic = "--automatic" in args or "--auto" in args
    
    try:
        # Find the preuninstall script
        preuninstall_script = framework_path / "install" / "preuninstall.js"
        
        if not preuninstall_script.exists():
            console.print("[red]❌ Cleanup script not found![/red]")
            console.print(f"   Expected: {preuninstall_script}")
            console.print("\n[bold]Manual cleanup required:[/bold]")
            console.print("   • Remove ~/.claude-pm/ directory")
            console.print("   • Remove ~/.local/bin/claude-pm")
            console.print("   • Remove global npm package: npm uninstall -g @bobmatnyc/claude-multiagent-pm")
            console.print("   • Remove pip package: pip uninstall claude-multiagent-pm")
            sys.exit(1)
        
        # Build cleanup command
        cleanup_cmd = ["node", str(preuninstall_script)]
        
        if interactive:
            cleanup_cmd.append("--interactive")
        elif automatic:
            cleanup_cmd.append("--automatic")
        else:
            # Default to interactive for safety
            cleanup_cmd.append("--interactive")
        
        console.print(f"[dim]Executing: {' '.join(cleanup_cmd)}[/dim]")
        console.print("")
        
        # Execute the cleanup script
        result = subprocess.run(cleanup_cmd, cwd=str(framework_path))
        
        if result.returncode == 0:
            console.print("\n[green]✅ Claude PM Framework cleanup completed successfully![/green]")
            console.print("[dim]🎉 All components have been removed from your system[/dim]")
            
            # Display post-cleanup information
            console.print("\n[bold]📋 What was cleaned up:[/bold]")
            console.print("   • NPM package installations")
            console.print("   • Python pip packages")
            console.print("   • CLI executables")
            console.print("   • Framework files and configurations")
            console.print("   • User data (if requested)")
            console.print("   • Memory and cache files")
            
            console.print("\n[dim]💡 To reinstall: npm install -g @bobmatnyc/claude-multiagent-pm[/dim]")
            sys.exit(0)
        else:
            console.print("\n[red]❌ Cleanup failed or was incomplete![/red]")
            console.print("[dim]Check the output above for errors[/dim]")
            sys.exit(1)
            
    except FileNotFoundError:
        console.print("[red]❌ Node.js not found![/red]")
        console.print("Node.js is required to run the cleanup script.")
        console.print("\n[bold]Manual cleanup alternatives:[/bold]")
        console.print("   • Install Node.js and retry")
        console.print("   • Manual removal of ~/.claude-pm/ directory")
        console.print("   • Manual removal of CLI executables")
        sys.exit(1)
    except Exception as e:
        console.print(f"[red]❌ Cleanup error: {e}[/red]")
        console.print("\n[bold]Manual cleanup may be required[/bold]")
        sys.exit(1)


def main():
    """Main entry point with pure Python implementation."""
    args = sys.argv[1:]
    
    # Enhanced flags that trigger Python CLI system
    enhanced_flags = ["--safe", "--upgrade", "--rollback", "--dry-run", "--cleanup", "--test-mode"]
    version_flags = ["--version"]  # Removed -v to avoid conflict with verbose
    help_flags = ["--help", "-h"]
    
    # Auto-initialize project .claude-pm directory if missing (except for cleanup/uninstall)
    # This prevents errors from missing log directories and other project structures
    cleanup_commands = ["--cleanup", "--uninstall", "uninstall", "cleanup"]
    is_cleanup_command = any(cmd in args for cmd in cleanup_commands)
    
    if not is_cleanup_command:
        # Silently ensure project is initialized before any operations
        ensure_project_initialized()
    
    # Check for init command
    if args and args[0] == "init":
        handle_init_command(args)
        return
    
    # Check for cleanup command
    if "--cleanup" in args:
        handle_cleanup_command(args)
        return
    
    # Check for test mode flag specifically or from environment
    test_mode = "--test-mode" in args or os.environ.get("CLAUDE_PM_TEST_MODE") == "true"
    
    # Remove --test-mode from args if present (it's not a Claude CLI flag)
    if "--test-mode" in args:
        args = [arg for arg in args if arg != "--test-mode"]
    
    # Check for enhanced flags (excluding test-mode from triggering enhanced flags handler)
    # test-mode should only go through enhanced flags when used with other enhanced flags
    has_enhanced_flags = any(
        arg in [f for f in enhanced_flags if f != "--test-mode"] or 
        arg.startswith("--format=") or
        any(flag in args for flag in [f for f in enhanced_flags if f != "--test-mode"])
        for arg in args
    )
    
    # Handle enhanced version command (with additional options)
    if any(flag in args for flag in version_flags) and (
        "--components" in args or 
        "--git" in args or 
        "--format" in " ".join(args) or
        "--detailed" in args or
        has_enhanced_flags
    ):
        handle_enhanced_flags()
        return
    
    # Handle enhanced flags
    if has_enhanced_flags:
        handle_enhanced_flags()
        return
    
    # Handle standalone --test-mode flag (when no other args present)
    if test_mode and not args:
        # Launch Claude CLI in YOLO mode with test mode enabled
        display_comprehensive_status()
        
        if not validate_framework_deployment():
            console.print("[red]❌ Claude PM Framework not properly deployed![/red]")
            console.print("[yellow]💡 Use 'claude-pm init' to initialize the framework[/yellow]")
            sys.exit(1)
        
        console.print("[green]✅ All systems validated - launching Claude CLI with test mode[/green]")
        console.print("")
        launch_claude_cli_yolo(test_mode=True)
        return
    
    # Handle basic flags
    if any(flag in args for flag in version_flags):
        package_version = get_framework_version()
        
        # Get framework/CLAUDE.md version using the framework_path defined above
        framework_version_file = framework_path / "framework" / "VERSION"
        framework_version = "unknown"
        if framework_version_file.exists():
            try:
                framework_version = framework_version_file.read_text().strip()
            except:
                pass
        
        console.print(f"[bold]claude-pm script version: {SCRIPT_VERSION}[/bold]")
        console.print(f"Package version: v{package_version}")
        console.print(f"Framework/CLAUDE.md version: {framework_version}")
        return
    
    if any(flag in args for flag in help_flags):
        show_help()
        return
    
    if "--system-info" in args:
        display_system_info()
        return
    
    if "--deployment-info" in args:
        display_deployment_info()
        return
    
    # Check for pass-through flags first
    passthrough_flags = ["--continue", "-c", "--resume", "-r"]
    if any(flag in args for flag in passthrough_flags):
        # Pass through continue/resume flags after validation
        display_comprehensive_status()
        
        if not validate_framework_deployment():
            console.print("[red]❌ Claude PM Framework not properly deployed![/red]")
            console.print("")
            
            # Attempt auto-installation first
            if attempt_auto_installation():
                console.print("[green]✅ Framework auto-installation successful![/green]")
                
                # Re-validate after auto-installation
                if validate_framework_deployment():
                    console.print("[green]✅ Framework deployment validated - proceeding...[/green]")
                else:
                    console.print("[red]❌ Framework deployment validation failed after auto-installation[/red]")
                    sys.exit(1)
            else:
                console.print("[bold]🚨 Framework deployment required before operations[/bold]")
                console.print("\n🛠️  [bold]Automatic Initialization Available[/bold]")
                console.print("Would you like to initialize the framework now? (y/N): ", end="")
                
                try:
                    response = input().strip().lower()
                    if response in ['y', 'yes']:
                        console.print("[dim]🚀 Starting automatic framework initialization...[/dim]")
                        handle_init_command([])
                        return
                except KeyboardInterrupt:
                    console.print("\n[yellow]Initialization cancelled by user[/yellow]")
                
                console.print("\n[bold]Manual initialization commands:[/bold]")
                console.print("   • claude-pm init                      (recommended)")
                console.print("   • claude-pm setup")
                console.print("   • claude-pm deploy")
                console.print("   • npm run install:unified (from framework directory)")
                console.print("")
                console.print(f"📍 Expected framework location: ~/.claude-pm")
                sys.exit(1)
        
        console.print("[green]✅ All systems validated - launching Claude CLI with pass-through flags[/green]")
        console.print("")
        launch_claude_cli_with_args(args, test_mode=test_mode)
        return
    
    # Handle no arguments case - Framework validation required per ISS-0112
    if not args:
        # ISS-0112: Require framework deployment before ANY operations
        display_comprehensive_status()
        
        if not validate_framework_deployment():
            console.print("[red]❌ Claude PM Framework not properly deployed![/red]")
            console.print("")
            
            # Attempt auto-installation first
            if attempt_auto_installation():
                console.print("[green]✅ Framework auto-installation successful![/green]")
                
                # Re-validate after auto-installation
                if validate_framework_deployment():
                    console.print("[green]✅ Framework deployment validated - proceeding...[/green]")
                else:
                    console.print("[red]❌ Framework deployment validation failed after auto-installation[/red]")
                    sys.exit(1)
            else:
                console.print("[bold]🚨 Framework deployment required before operations[/bold]")
                console.print("\n🛠️  [bold]Automatic Initialization Available[/bold]")
                console.print("Would you like to initialize the framework now? (y/N): ", end="")
                
                try:
                    response = input().strip().lower()
                    if response in ['y', 'yes']:
                        console.print("[dim]🚀 Starting automatic framework initialization...[/dim]")
                        handle_init_command([])
                        return
                except KeyboardInterrupt:
                    console.print("\n[yellow]Initialization cancelled by user[/yellow]")
                
                console.print("\n[bold]Manual initialization commands:[/bold]")
                console.print("   • claude-pm init                      (recommended)")
                console.print("   • claude-pm setup")
                console.print("   • claude-pm deploy")
                console.print("   • npm run install:unified (from framework directory)")
                console.print("")
                console.print(f"📍 Expected framework location: ~/.claude-pm")
                sys.exit(1)
        
        console.print("[green]✅ All systems validated - launching Claude CLI in YOLO mode[/green]")
        console.print("")
        # Framework validated - launch Claude CLI in proper YOLO mode
        launch_claude_cli_yolo(test_mode=test_mode)
        return
    
    # Handle case where --test-mode is used with other arguments
    if test_mode and args:
        # Pass through to Claude CLI with test mode enabled
        display_comprehensive_status()
        
        if not validate_framework_deployment():
            console.print("[red]❌ Claude PM Framework not properly deployed![/red]")
            console.print("[yellow]💡 Use 'claude-pm init' to initialize the framework[/yellow]")
            sys.exit(1)
        
        console.print("[green]✅ All systems validated - launching Claude CLI with test mode[/green]")
        console.print("")
        launch_claude_cli_with_args(args, test_mode=test_mode)
        return
    
    # For other commands, delegate to Python framework
    deployment_info = detect_deployment_type()
    deployment_framework_path = deployment_info["framework_path"]
    
    try:
        # Use subprocess to call the Python CLI module
        cmd = [sys.executable, "-m", "claude_pm.cli"] + args
        result = subprocess.run(cmd, cwd=deployment_framework_path)
        
        # Check if the command failed due to missing module
        if result.returncode != 0:
            # Try to test if module is importable
            test_import = subprocess.run([
                sys.executable, "-c", "import claude_pm"
            ], capture_output=True, cwd=deployment_framework_path)
            
            if test_import.returncode != 0:
                console.print("[yellow]⚠️  Python module not found - attempting installation...[/yellow]")
                if attempt_python_package_installation():
                    console.print("[green]✅ Package installed! Please run the command again.[/green]")
                    sys.exit(0)
                else:
                    console.print("[red]❌ Automatic installation failed[/red]")
                    console.print("\n[bold]🔧 Manual installation required:[/bold]")
                    console.print("   1. Navigate to the framework directory:")
                    console.print(f"      cd {deployment_framework_path}")
                    console.print("   2. Install the Python package:")
                    console.print("      pip install -e .")
                    console.print("   3. Then retry the command")
                    sys.exit(1)
        
        sys.exit(result.returncode)
        
    except Exception as e:
        console.print(f"[red]❌ Failed to execute Claude PM Framework: {e}[/red]")
        console.print(f"   Framework path: {deployment_framework_path}")
        console.print(f"   Python command: {sys.executable}")
        sys.exit(1)


if __name__ == "__main__":
    main()