import argparse
import sys
from typing import List
from datetime import datetime
from .tree_generator import DirectoryTreeGenerator, __version__

def parse_exclude_list(exclude_str: str) -> List[str]:
    """Parse comma-separated exclude list."""
    if not exclude_str:
        return []
    return [item.strip() for item in exclude_str.split(',') if item.strip()]

def main():
    parser = argparse.ArgumentParser(
        description='Generate ASCII tree representation of directory structure',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        epilog=""" Examples:   
  pygentree                     # Generate tree for current directory
  pygentree /path/to/dir       # Generate tree for specific directory
  pygentree -l 2              # Limit depth to 2 levels
  pygentree -s desc           # Sort in descending order
  pygentree -d                # Show only directories
  pygentree -o tree.txt       # Save output to text file
  pygentree -o tree.rst       # Save output to reStructuredText file
  pygentree --ignore-hidden   # Ignore hidden files and directories
  pygentree -e "node_modules,venv,dist"  # Exclude specific files/directories
        """
    )
    
    parser.add_argument('path', nargs='?', default='.',
                        help='Root directory path (default: current directory)')
    parser.add_argument('-l', '--level', type=int,
                        help='Maximum depth level to traverse')
    parser.add_argument('-s', '--sort', choices=['asc', 'desc', 'standard'],
                        default='standard',
                        help='Sort order (asc, desc, or standard)')
    parser.add_argument('-d', '--dirs-only', action='store_true',
                        help='Show only directories, ignore files')
    parser.add_argument('-o', '--output',
                        help='Output file path to save the tree')
    parser.add_argument('--format', choices=['txt', 'rst'], default='txt',
                        help='Output file format (default: txt)')
    parser.add_argument('--ignore-hidden', action='store_true',
                        help='Ignore hidden files and directories')
    parser.add_argument('-e', '--exclude',
                        help='Comma-separated list of files/directories to exclude')
    parser.add_argument('-v', '--version', action='version',
                        version=f'PyGenTree v{__version__}')
    
    args = parser.parse_args()
    
    try:
        exclude_list = parse_exclude_list(args.exclude)
        
        generator = DirectoryTreeGenerator(
            args.path,
            max_level=args.level,
            sort_order=args.sort,
            dirs_only=args.dirs_only,
            ignore_hidden=args.ignore_hidden,
            exclude=exclude_list
        )
        
        # Automatically add the correct file extension if not provided
        if args.output and not args.output.endswith(('.' + args.format)):
            output_file = f"{args.output}.{args.format}"
        else:
            output_file = args.output or f"tree.{args.format}"
        
        # Modify save_tree method to support different formats
        def save_tree_with_format(tree_content, output_file):
            with open(output_file, 'w', encoding='utf-8') as f:
                if args.format == 'rst':
                    # Add RST header formatting
                    f.write(f"Directory Tree\n{'=' * 15}\n\n")
                    f.write(f"Generated by PyGenTree v{__version__}\n\n")
                    f.write(".. code-block:: text\n\n")
                    # Indent each line for RST code block
                    f.write('\n'.join(f"    {line}" for line in tree_content.split('\n')))
                else:
                    # Existing text file format
                    f.write(f"Directory Tree generated by PyGenTree v{__version__}\n")
                    f.write(f"Generated on: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
                    f.write(f"Root directory: {generator.root_dir.absolute()}\n")
                    f.write(f"Options: depth={generator.max_level or 'unlimited'}, ")
                    f.write(f"sort={generator.sort_order}, ")
                    f.write(f"dirs_only={generator.dirs_only}, ")
                    f.write(f"ignore_hidden={generator.ignore_hidden}, ")
                    f.write(f"excluded={list(generator.exclude) or 'none'}\n")
                    f.write("-" * 50 + "\n\n")
                    f.write(tree_content)
        
        if args.output:
            tree_content = generator.get_tree()
            save_tree_with_format(tree_content, output_file)
            print(f"Tree saved to: {output_file}")
        else:
            print(generator.get_tree())
    
    except Exception as e:
        print(f"Error: {str(e)}", file=sys.stderr)
        sys.exit(1)

if __name__ == '__main__':
    main()