"""
Project commands for Metis Agent CLI.

Provides project scaffolding and management commands.
"""

import click
import os
from typing import Dict, Any

from ..tools.project_scaffolding import ProjectScaffoldingTool


@click.group()
def project():
    """Project scaffolding and management commands."""
    pass


@project.command()
@click.argument('project_type')
@click.argument('project_name')
@click.option('--cwd', default='.', help='Directory to create project in')
def init(project_type: str, project_name: str, cwd: str):
    """Initialize a new project with the specified type and name.
    
    PROJECT_TYPE: python, node, fastapi, etc.
    PROJECT_NAME: Name of the project to create
    """
    cwd = os.path.abspath(cwd)
    
    if not os.path.exists(cwd):
        click.echo(f"Error: Directory '{cwd}' does not exist", err=True)
        return
    
    tool = ProjectScaffoldingTool()
    task = f"create {project_type} project"
    result = tool.execute(task, cwd=cwd, project_name=project_name)
    
    if not result.get("success"):
        click.echo(f"Error: {result.get('error')}", err=True)
        return
    
    click.echo(f"Successfully created {result.get('project_type', 'project')}: {project_name}")
    click.echo(f"Location: {result.get('project_path', 'unknown')}")
    
    # Show created files
    files_created = result.get("files_created", [])
    if files_created:
        click.echo(f"\nFiles created ({len(files_created)}):")
        for file in files_created:
            click.echo(f"  + {file}")
    
    # Show next steps
    next_steps = result.get("next_steps", [])
    if next_steps:
        click.echo(f"\nNext steps:")
        for i, step in enumerate(next_steps, 1):
            click.echo(f"  {i}. {step}")


@project.command()
@click.option('--cwd', default='.', help='Working directory')
def setup(cwd: str):
    """Setup development tooling for an existing project."""
    cwd = os.path.abspath(cwd)
    
    if not os.path.exists(cwd):
        click.echo(f"Error: Directory '{cwd}' does not exist", err=True)
        return
    
    tool = ProjectScaffoldingTool()
    result = tool.execute("setup existing project", cwd=cwd)
    
    if not result.get("success"):
        click.echo(f"Error: {result.get('error')}", err=True)
        if result.get("suggestion"):
            click.echo(f"Suggestion: {result.get('suggestion')}")
        return
    
    click.echo(result.get("message", "Project setup completed"))
    
    # Show created files
    files_created = result.get("files_created", [])
    if files_created:
        click.echo(f"\nFiles created/updated:")
        for file in files_created:
            click.echo(f"  + {file}")
    
    # Show suggestions
    suggestions = result.get("suggestions", [])
    if suggestions:
        click.echo(f"\nRecommended next steps:")
        for suggestion in suggestions:
            click.echo(f"  - {suggestion}")


@project.command()
def types():
    """List available project types and examples."""
    tool = ProjectScaffoldingTool()
    result = tool.execute("list project types")
    
    if not result.get("success"):
        click.echo(f"Error: {result.get('error')}", err=True)
        return
    
    click.echo("Available Project Types")
    click.echo("=" * 50)
    
    available_types = result.get("available_types", [])
    for project_type in available_types:
        click.echo(f"  {project_type}")
    
    click.echo(f"\nExamples:")
    examples = result.get("examples", [])
    for example in examples:
        click.echo(f"  {example}")


@project.command()
@click.argument('template_name')
@click.argument('project_name')
@click.option('--cwd', default='.', help='Directory to create project in')
def create(template_name: str, project_name: str, cwd: str):
    """Create a project from a specific template.
    
    TEMPLATE_NAME: Template to use (python, fastapi, node, etc.)
    PROJECT_NAME: Name of the project to create
    """
    # This is an alias for the init command
    ctx = click.get_current_context()
    ctx.invoke(init, project_type=template_name, project_name=project_name, cwd=cwd)


@project.command()
@click.option('--cwd', default='.', help='Working directory')
def info(cwd: str):
    """Show information about the current project."""
    cwd = os.path.abspath(cwd)
    
    if not os.path.exists(cwd):
        click.echo(f"Error: Directory '{cwd}' does not exist", err=True)
        return
    
    # Detect project type and show information
    project_files = {
        "Python": ["requirements.txt", "setup.py", "pyproject.toml", "Pipfile"],
        "Node.js": ["package.json"],
        "Git": [".git"]
    }
    
    detected_types = []
    for project_type, files in project_files.items():
        for file in files:
            if os.path.exists(os.path.join(cwd, file)):
                detected_types.append(project_type)
                break
    
    click.echo(f"Project Information")
    click.echo("=" * 50)
    click.echo(f"Directory: {cwd}")
    
    if detected_types:
        click.echo(f"Detected types: {', '.join(detected_types)}")
    else:
        click.echo("No known project types detected")
    
    # Show directory contents
    try:
        contents = os.listdir(cwd)
        important_files = [f for f in contents if f in [
            "README.md", "requirements.txt", "package.json", "setup.py", 
            "pyproject.toml", ".gitignore", "Makefile", ".git"
        ]]
        
        if important_files:
            click.echo(f"\nImportant files found:")
            for file in important_files:
                click.echo(f"  + {file}")
        
        # Count files and directories
        files = [f for f in contents if os.path.isfile(os.path.join(cwd, f))]
        dirs = [f for f in contents if os.path.isdir(os.path.join(cwd, f)) and not f.startswith('.')]
        
        click.echo(f"\nDirectory structure:")
        click.echo(f"  Files: {len(files)}")
        click.echo(f"  Directories: {len(dirs)}")
        
    except PermissionError:
        click.echo("Cannot access directory contents")


# Add commands to the main CLI
def add_project_commands(cli):
    """Add project commands to the main CLI."""
    cli.add_command(project)
