# Licensed under a 3-clause BSD style license - see LICENSE.rst

"""
Utilities for generating the version string for Astropy (or an affiliated
package) and the version.py module, which contains version info for the
package.

Within the generated astropy.version module, the `major`, `minor`, and `bugfix`
variables hold the respective parts of the version number (bugfix is '0' if
absent). The `release` variable is True if this is a release, and False if this
is a development version of astropy. For the actual version string, use::

    from astropy.version import version

or::

    from astropy import __version__

"""

from __future__ import division

import datetime
import imp
import os
import pkgutil
import sys

from distutils import log

from . import git_helpers
from .setup_helpers import is_distutils_display_option, get_pkg_version_module
from .utils import invalidate_caches

PY3 = sys.version_info[0] == 3



def _version_split(version):
    """
    Split a version string into major, minor, and bugfix numbers (with bugfix
    optional, defaulting to 0).
    """

    for prerel in ('.dev', 'a', 'b', 'rc'):
        if prerel in version:
            version = version.split(prerel)[0]

    versplit = version.split('.')
    major = int(versplit[0])
    minor = int(versplit[1])
    bugfix = 0 if len(versplit) < 3 else int(versplit[2])
    return major, minor, bugfix


# This is used by setup.py to create a new version.py - see that file for
# details. Note that the imports have to be absolute, since this is also used
# by affiliated packages.
_FROZEN_VERSION_PY_TEMPLATE = """
# Autogenerated by {packagename}'s setup.py on {timestamp}

{header}

major = {major}
minor = {minor}
bugfix = {bugfix}

release = {rel}
debug = {debug}

try:
    from ._compiler import compiler
except ImportError:
    compiler = "unknown"

try:
    from .cython_version import cython_version
except ImportError:
    cython_version = "unknown"
"""[1:]


_FROZEN_VERSION_PY_WITH_GIT_HEADER = """
{git_helpers}

_last_generated_version = {verstr!r}

version = update_git_devstr(_last_generated_version)
githash = get_git_devstr(sha=True, show_warning=False)
"""[1:]


def _get_version_py_str(packagename, version, release, debug, uses_git=True):
    timestamp = str(datetime.datetime.now())
    major, minor, bugfix = _version_split(version)

    if packagename.lower() == 'astropy':
        packagename = 'Astropy'
    else:
        packagename = 'Astropy-affiliated package ' + packagename

    if uses_git:
        loader = pkgutil.get_loader(git_helpers)
        source = loader.get_source(git_helpers.__name__) or ''
        source_lines = source.splitlines()
        if not source_lines:
            log.warn('Cannot get source code for astropy_helpers.git_helpers; '
                     'git support disabled.')
            return _get_version_py_str(packagename, version, release, debug,
                                       uses_git=False)
        idx = 0
        for idx, line in enumerate(source_lines):
            if line.startswith('# BEGIN'):
                break
        git_helpers_py = '\n'.join(source_lines[idx + 1:])

        if PY3:
            verstr = version
        else:
            # In Python 2 don't pass in a unicode string; otherwise verstr will
            # be represented with u'' syntax which breaks on Python 3.x with x
            # < 3.  This is only an issue when developing on multiple Python
            # versions at once
            verstr = version.encode('utf8')

        header = _FROZEN_VERSION_PY_WITH_GIT_HEADER.format(
                git_helpers=git_helpers_py,
                verstr=verstr)
    else:
        header = 'version = {0!r}'.format(version)

    return _FROZEN_VERSION_PY_TEMPLATE.format(packagename=packagename,
                                              timestamp=timestamp,
                                              header=header,
                                              major=major,
                                              minor=minor,
                                              bugfix=bugfix,
                                              rel=release, debug=debug)


def generate_version_py(packagename, version, release=None, debug=None,
                        uses_git=True):
    """Regenerate the version.py module if necessary."""

    try:
        version_module = get_pkg_version_module(packagename)

        try:
            last_generated_version = version_module._last_generated_version
        except AttributeError:
            last_generated_version = version_module.version

        current_release = version_module.release
        current_debug = version_module.debug
    except ImportError:
        version_module = None
        last_generated_version = None
        current_release = None
        current_debug = None

    if release is None:
        # Keep whatever the current value is, if it exists
        release = bool(current_release)

    if debug is None:
        # Likewise, keep whatever the current value is, if it exists
        debug = bool(current_debug)

    version_py = os.path.join(packagename, 'version.py')

    if (last_generated_version != version or current_release != release or
        current_debug != debug):
        if '-q' not in sys.argv and '--quiet' not in sys.argv:
            log.set_threshold(log.INFO)

        if is_distutils_display_option():
            # Always silence unnecessary log messages when display options are
            # being used
            log.set_threshold(log.WARN)

        log.info('Freezing version number to {0}'.format(version_py))

        with open(version_py, 'w') as f:
            # This overwrites the actual version.py
            f.write(_get_version_py_str(packagename, version, release, debug,
                                        uses_git=uses_git))

        invalidate_caches()

        if version_module:
            imp.reload(version_module)
