"""Command-line interface for BatGenie."""
import click
import os
import shutil
from pathlib import Path
import logging
from typing import Optional
import json
from rich.console import Console
from rich.panel import Panel
from rich.prompt import Prompt, Confirm

from .intelligence_manager import IntelligenceManager, IntelligenceConfig
from .context_manager import ContextManager

console = Console()
logger = logging.getLogger(__name__)

def setup_project_structure(path: Path):
    """Set up the basic project structure."""
    # Create project directories
    dirs = [
        '.cursor',
        '.cursor/cache',
        '.cursor/tools',
        'docs',
        'tests',
        'scripts'
    ]
    for dir_path in dirs:
        (path / dir_path).mkdir(parents=True, exist_ok=True)

def copy_template_files(path: Path):
    """Copy template files to the project."""
    template_dir = Path(__file__).parent / 'templates'
    files_to_copy = [
        'README.md',
        'requirements.txt',
        'setup.py',
        '.gitignore',
        'pytest.ini',
        '.pre-commit-config.yaml'
    ]
    for file in files_to_copy:
        if (template_dir / file).exists():
            shutil.copy2(template_dir / file, path / file)

@click.group()
def cli():
    """BatGenie - Your AI-Powered Development Companion."""
    pass

@cli.command()
@click.argument('project_path', type=click.Path())
@click.option('--template', type=str, help='Project template to use')
@click.option('--description', type=str, help='Project description')
def init(project_path: str, template: Optional[str], description: Optional[str]):
    """Initialize a new project with BatGenie."""
    path = Path(project_path)
    
    # Create project directory if it doesn't exist
    path.mkdir(parents=True, exist_ok=True)
    
    console.print(Panel.fit("🧞‍♂️ Initializing BatGenie project...", title="BatGenie"))
    
    # Set up project structure
    setup_project_structure(path)
    
    # Copy template files
    copy_template_files(path)
    
    # Initialize git if not already initialized
    if not (path / '.git').exists():
        os.system(f'cd {path} && git init')
    
    # Get project description if not provided
    if not description:
        description = Prompt.ask(
            "Please provide a brief description of your project",
            default="A new project powered by BatGenie"
        )
    
    # Initialize intelligence manager
    config = IntelligenceConfig(
        workspace_root=str(path),
        enable_auto_learning=True,
        enable_goal_tracking=True,
        enable_resource_caching=True,
        enable_clarification=True
    )
    
    intelligence_manager = IntelligenceManager(config)
    
    # Start project analysis
    console.print("\n🔍 Analyzing project requirements...")
    
    # Ask clarifying questions about the project
    questions = [
        ("What type of application are you building?", "type"),
        ("What are the main technical requirements?", "requirements"),
        ("Who are the target users?", "users"),
        ("What are the key features needed?", "features")
    ]
    
    answers = {}
    for question, key in questions:
        answers[key] = Prompt.ask(question)
    
    # Record project context
    context_manager = ContextManager(str(path))
    context_manager.update_project_context({
        'project': {
            'name': path.name,
            'description': description,
            'type': answers['type'],
            'requirements': answers['requirements'],
            'target_users': answers['users'],
            'key_features': answers['features'],
            'created_at': datetime.now().isoformat()
        }
    })
    
    console.print("\n✨ Project initialized successfully!")
    console.print("\nNext steps:")
    console.print("1. Review and edit the generated README.md")
    console.print("2. Install dependencies: pip install -r requirements.txt")
    console.print("3. Start developing with BatGenie's assistance")

@cli.command()
@click.argument('project_path', type=click.Path(exists=True))
def integrate(project_path: str):
    """Integrate BatGenie with an existing project."""
    path = Path(project_path)
    
    console.print(Panel.fit("🧞‍♂️ Integrating BatGenie...", title="BatGenie"))
    
    # Set up BatGenie directories
    setup_project_structure(path)
    
    # Initialize intelligence manager
    config = IntelligenceConfig(
        workspace_root=str(path),
        enable_auto_learning=True,
        enable_goal_tracking=True,
        enable_resource_caching=True,
        enable_clarification=True
    )
    
    intelligence_manager = IntelligenceManager(config)
    
    # Analyze existing project
    console.print("\n🔍 Analyzing existing project...")
    
    # Check for existing documentation
    docs_path = path / 'docs'
    readme_path = path / 'README.md'
    
    if docs_path.exists():
        console.print("📚 Found documentation directory, analyzing...")
        # TODO: Analyze documentation
    
    if readme_path.exists():
        console.print("📖 Found README.md, analyzing...")
        # TODO: Analyze README
    
    # Ask for additional context
    should_ask = Confirm.ask("Would you like to provide additional context about the project?")
    if should_ask:
        description = Prompt.ask("Please describe the project's purpose")
        tech_stack = Prompt.ask("What is the main technology stack?")
        challenges = Prompt.ask("What are the current challenges or areas needing improvement?")
        
        # Record project context
        context_manager = ContextManager(str(path))
        context_manager.update_project_context({
            'project': {
                'name': path.name,
                'description': description,
                'tech_stack': tech_stack,
                'challenges': challenges,
                'integrated_at': datetime.now().isoformat()
            }
        })
    
    console.print("\n✨ BatGenie integrated successfully!")
    console.print("\nNext steps:")
    console.print("1. Review the generated .cursor directory")
    console.print("2. Start using BatGenie's assistance in your development")

if __name__ == '__main__':
    cli() 