import click
import os
from viper_ccm.languages import guess_language, parse
from viper_ccm.formatter import get_formatter


@click.command()
@click.argument('path', type=click.Path(exists=True))
@click.option('--fqdn', is_flag=True, default=False, help='Show fully qualified names.')
@click.option('--format', 'fmt', default='default', type=click.Choice(['default', 'pmccabe']),
              help='Output format.')
def main(path, fqdn, fmt):
    """Analyze source code files to compute cyclomatic complexity metrics."""

    formatter = get_formatter(fmt, fqdn=fqdn) if fmt == 'default' else get_formatter(fmt)

    # Collect files
    if os.path.isfile(path):
        files = [path]
    else:
        files = []
        for root, dirs, filenames in os.walk(path):
            for filename in filenames:
                filepath = os.path.join(root, filename)
                try:
                    guess_language(filepath)
                    files.append(filepath)
                except ValueError:
                    pass

    # Process each file
    for filepath in files:
        try:
            code = open(filepath, 'rb').read()
            lang = guess_language(filepath)
            functions = parse(code, lang=lang)
            output = formatter.format_file(filepath, lang, functions)
            click.echo(output)
        except Exception as e:
            click.echo(f"Error analyzing {filepath}: {e}", err=True)

if __name__ == "__main__":
    main()
