#! /usr/bin/env python
import os
import pprint
from abjad import abjad_configuration
from abjad.tools import systemtools


def find_local_import_statements():
    total_local_import_statements = 0
    for path, subdirectories, files in os.walk('.'):
        if '.svn' not in path and 'docs' not in path:
            for f in files:
                if f.endswith('.py') and not f == '__init__.py':
                    full_file_name = os.path.join(path, f)
                    result = find_local_import_statements_in_file(
                        full_file_name)
                    total_local_import_statements += result

    total = total_local_import_statements
    print 'Total local import statements: {}'.format(total)
    print


def find_local_import_statements_in_file(full_file_name):
    total_local_import_statements = 0
    file_parts = full_file_name.split(os.path.sep)
    module = file_parts[-2]
    function = file_parts[-1]
    shorter_module_name = '{}{}{}'.format(module, os.path.sep, function)
    fp = file(full_file_name, 'r')
    for line in fp.readlines():
        if line.startswith('from') and \
            not line.startswith('from experimental import *') and \
            not line.startswith(
                'from make_illustration_from_output_material') and \
            not line.startswith('from _'):
            line_parts = line.split()
            module_name = line_parts[1]
            if not module_name in ('abjad', '__future__'):
                if '.' not in module_name:
                    if total_local_import_statements == 0:
                        print shorter_module_name
                        total_local_import_statements += 1
                    print line.strip()
    fp.close()
    if 0 < total_local_import_statements:
        print
    return total_local_import_statements


if __name__ == '__main__':
    systemtools.IOManager.clear_terminal()
    find_local_import_statements()
