#!/usr/bin/env python
from __future__ import print_function
import os
import glob
from os.path import join, dirname, abspath, basename
import warnings

import relstorage

warnings.simplefilter('ignore', DeprecationWarning)


# do not generate .rst for the following modules
SKIP = []


template = '''.. AUTOGENERATED -- will be overwritten (remove this comment to save changes)

%(title)s
%(title_underline)s

.. automodule:: relstorage.%(module)s
    :members:
    :undoc-members:
'''

directory = dirname(abspath(relstorage.__file__))
print('Imported relstorage from %s' % (directory, ))
modules = glob.glob(join(directory, '*.py'))
modules = set(basename(filename).split('.')[0] for filename in modules)
adap_mods = {'adapters.' + basename(x).split('.')[0]
             for x in glob.glob(join(directory, 'adapters', '*.py'))
             if not basename(x).startswith("_")}
modules = modules.union(adap_mods)

for driver in 'mysql', 'oracle', 'postgresql', 'sqlite':
    adap_mods = {'adapters.' + driver + '.' + basename(x).split('.')[0]
                 for x in glob.glob(join(directory, 'adapters', driver, '*.py'))
                 if not basename(x).startswith("_")}
    modules = modules.union(adap_mods)

cache_mods = {'cache.' + basename(x).split('.')[0]
              for x in glob.glob(join(directory, 'cache', '*.py'))
              if not basename(x).startswith("_")}

modules = modules.union(cache_mods)


modules = set(name for name in modules
              if not name.startswith('_'))



def _read(fname, count):
    with open(fname) as f:
        return f.read(count)


def generate_rst_for_module(module, do=True):
    doc_name = 'relstorage.%s' % module
    rst_filename = doc_name + '.rst'
    exists = os.path.exists(rst_filename)
    if exists:
        autogenerated = 'autogenerated' in _read(rst_filename, 200).lower()
        if not autogenerated:
            return doc_name

    if '.' in module:
        m = __import__('relstorage.%s' % module, fromlist=['chicken'])
    else:
        m = __import__('relstorage.%s' % module)
        m = getattr(m, module)
    title = getattr(m, '__doc__', None)
    if title:
        lines = title.strip().splitlines()
        for line in lines:
            # skip leading blanks. Support both styles of docstrings.
            if line:
                title = line.strip()
                break
        title = title.strip(' .')
    prefix = ':mod:`relstorage.%s`' % module

    if title:
        title = prefix + ' -- %s' % (title, )
    else:
        title = prefix
    title_underline = '=' * len(title) # pylint:disable=possibly-unused-variable

    params = globals().copy()
    params.update(locals())
    result = template % params
    if getattr(m, '_no_undoc_members', True):
        result = '\n'.join(result.splitlines()[:-1])

    if exists:
        if _read(rst_filename, len(result) + 1) == result:
            return doc_name # already exists one which is the same

    if do:
        print('Generated %s from %s' % (rst_filename, m.__file__))
        with open(rst_filename, 'w') as f:
            f.write(result)
    else:
        print('Would generate %s from %s' % (rst_filename, m.__file__))
    return doc_name


index_template = '''\
================
Internal Details
================

.. caution:: This document is a reference for exploring the code base and
             tracing errors. The details are subject to change.

.. toctree::

'''

def generate_rst(do=True):
    assert os.path.exists('contents.rst'), 'Wrong directory, contents.rst not found'
    documents = []
    for module in modules:
        if module not in SKIP:
            try:
                document = generate_rst_for_module(module, do=do)
            except AttributeError as e:
                print("Failed to generate rst for", module, e, "; skipping")
            else:
                documents.append(document)

    documents.sort()
    with open('internals.rst', 'w') as f:
        f.write(index_template)
        for doc in documents:
            f.write('   ' + doc + '\n')

    return documents


def iter_autogenerated():
    for module in sorted(modules):
        rst_filename = 'relstorage.%s.rst' % module
        exists = os.path.exists(rst_filename)
        if exists:
            autogenerated = 'autogenerated' in open(rst_filename).read(200).lower()
            if autogenerated:
                yield rst_filename


if __name__ == '__main__':
    import sys
    if sys.argv[1:] == ['show']:
        for filename in iter_autogenerated():
            print(filename)
    elif sys.argv[1:] == ['delete']:
        for filename in iter_autogenerated():
            print('Removing', filename)
            os.unlink(filename)
    elif sys.argv[1:] == ['generate']:
        generate_rst()
    elif sys.argv[1:] == []:
        generate_rst(do=False)
    else:
        sys.exit('Invalid command line: %s' % (sys.argv[1:], ))
