"""CLI implementation for the Naiogram package."""
import argparse
import os
import sys
import shutil


def copy_template(template_name, project_name, destination):
    """Copy template directory to destination, substituting {name} placeholders."""
    pkg_dir = os.path.dirname(__file__)
    template_path = os.path.join(pkg_dir, 'templates', template_name)
    
    if not os.path.exists(template_path):
        print(f"Template '{template_name}' not found.", file=sys.stderr)
        print(f"Looking in: {template_path}", file=sys.stderr)
        available = []
        templates_dir = os.path.join(pkg_dir, 'templates')
        if os.path.exists(templates_dir):
            available = [d for d in os.listdir(templates_dir) 
                        if os.path.isdir(os.path.join(templates_dir, d))]
        if available:
            print(f"Available templates: {', '.join(available)}", file=sys.stderr)
        return 1
    
    # Create destination if needed
    os.makedirs(destination, exist_ok=True)
    
    # Walk and copy all files
    for dirpath, dirnames, filenames in os.walk(template_path):
        # Calculate relative path from template root
        rel_dir = os.path.relpath(dirpath, template_path)
        target_dir = os.path.join(destination, rel_dir) if rel_dir != '.' else destination
        
        # Create target directory
        os.makedirs(target_dir, exist_ok=True)
        
        for filename in filenames:
            src_file = os.path.join(dirpath, filename)
            dst_file = os.path.join(target_dir, filename)
            
            # Try to read as text and substitute placeholders
            try:
                with open(src_file, 'r', encoding='utf-8') as f:
                    content = f.read()
                content = content.replace('{name}', project_name)
                with open(dst_file, 'w', encoding='utf-8') as f:
                    f.write(content)
            except UnicodeDecodeError:
                # Binary file - copy as-is
                shutil.copy2(src_file, dst_file)
    
    print(f"Created project '{project_name}' from template '{template_name}' at {destination}")
    return 0


def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    parser = argparse.ArgumentParser(
        prog='naiogram',
        description='Naiogram - Telegram bot project templater'
    )
    sub = parser.add_subparsers(dest='command')

    # template command
    p_template = sub.add_parser('template', help='Create a project from a template')
    p_template.add_argument('template_name', help='Template name (e.g. clean, basic)')
    p_template.add_argument('project_name', help='Project name')
    p_template.add_argument('destination', nargs='?', 
                           help='Destination directory (default: current directory)')

    args = parser.parse_args(argv)

    if args.command == 'template':
        dest = args.destination or os.getcwd()
        return copy_template(args.template_name, args.project_name, dest)
    else:
        parser.print_help()
        return 0


if __name__ == '__main__':
    sys.exit(main() or 0)
