"""CLI interface for tagitmd using Click."""

import sys
from pathlib import Path
import click
from tagitmd.core import add_tags_to_file, find_markdown_files


@click.command()
@click.argument('tags', nargs=-1, required=True)
@click.option(
    '--path',
    '-p',
    default='.',
    type=click.Path(exists=True, file_okay=False, dir_okay=True, path_type=Path),
    help='Directory to process (default: current directory)'
)
@click.option(
    '--dry-run',
    is_flag=True,
    help='Preview changes without modifying files'
)
@click.option(
    '--only-untagged',
    is_flag=True,
    help='Only modify files without existing tags'
)
@click.option(
    '--recursive/--no-recursive',
    default=True,
    help='Search recursively in subdirectories (default: True)'
)
def main(tags: tuple, path: Path, dry_run: bool, only_untagged: bool, recursive: bool):
    """
    Add tags to markdown frontmatter.
    
    TAGS: One or more tags to add to markdown files (e.g., "python tutorial")
    """
    tags_list = list(tags)
    
    if dry_run:
        click.echo("=== DRY RUN MODE - No files will be modified ===")
        click.echo()
    
    modified_count = 0
    skipped_count = 0
    error_count = 0
    
    try:
        markdown_files = find_markdown_files(path, recursive=recursive)
    except Exception as e:
        click.echo(f"ERROR: Failed to find markdown files: {str(e)}", err=True)
        sys.exit(1)
    
    if not markdown_files:
        click.echo(f"No markdown files found in {path}")
        sys.exit(0)
    
    for filepath in markdown_files:
        was_modified, message = add_tags_to_file(
            filepath, 
            tags_list, 
            only_untagged,
            dry_run=dry_run
        )
        
        click.echo(message)
        
        if was_modified:
            modified_count += 1
        elif message.startswith("ERROR"):
            error_count += 1
        else:
            skipped_count += 1
    
    click.echo()
    click.echo("=== Summary ===")
    click.echo(f"Modified: {modified_count}")
    click.echo(f"Skipped: {skipped_count}")
    click.echo(f"Errors: {error_count}")
    
    if dry_run and modified_count > 0:
        click.echo()
        click.echo("Run without --dry-run to apply changes.")
    
    if error_count > 0:
        sys.exit(1)
    
    sys.exit(0)


if __name__ == '__main__':
    main()
