# record tag number and git hash into a git_verinfo.py file.
#
import os
import sys
import datetime as dt
import git

# get location of the GSAS-II files
# assumed to be the parent of location of this file
path2GSAS2 = os.path.dirname(os.path.dirname(
    os.path.abspath(os.path.expanduser(__file__))))
# and the repo is in the parent of that
path2repo = os.path.dirname(path2GSAS2)

if __name__ == '__main__':

    g2repo = git.Repo(path2repo)
    # for now allow this to be used on the develop branch
    #if g2repo.active_branch.name != 'master':
    #    print(f'Not on master branch {commit0[:6]!r}')
    #    sys.exit()

    # create a file with GSAS-II version information
    try:
        g2repo = git.Repo(path2repo)
    except:
        print('Launch of gitpython for version file failed'+
                  f' with path {path2repo}')
        sys.exit()
    commit = g2repo.head.commit
    commitm1 = '?'
    tagsm1 = None
    #ctim = commit.committed_datetime.strftime('%d-%b-%Y %H:%M')
    now = dt.datetime.now().replace(
        tzinfo=commit.committed_datetime.tzinfo)
    commit0 = commit.hexsha

    #tags0 = g2repo.git.tag('--points-at',commit).split('\n')
    tags0 = [i for i in g2repo.git.tag('--points-at',commit).split('\n') if i.isdecimal()]
    history = list(g2repo.iter_commits('HEAD'))
    for i in history[1:]:
        tags = g2repo.git.tag('--points-at',i)
        if not tags: continue
        commitm1 = i.hexsha
        #tagsm1 = tags.split('\n')
        tagsm1 = [i for i in tags.split('\n') if i.isdecimal()]
        if not tagsm1: continue
        break
    # get the latest version number
    releases = [i for i in g2repo.tags if '.' in i.name and i.name.startswith('v')]
    if releases:
        majors = [i.name.split('.')[0][1:] for i in releases]
        major = max([int(i) for i in majors if i.isdecimal()])
        minors = [i.name.split('.')[1] for i in releases if i.name.startswith(f'v{major}.')]
        minor = max([int(i) for i in minors if i.isdecimal()])
        minis = [i.name.split('.',2)[2] for i in releases if i.name.startswith(f'v{major}.{minor}')]
        # mini can be integer, float or even have letters (5.2.1.1rc1)
        # for now, ignore anything with letters or decimals
        mini = max([int(i) for i in minis if i.isdecimal()])
        versiontag = f'v{major}.{minor}.{mini}'
    else:
        versiontag = '?'
    # create a file with GSAS-II version information
    pyfile = os.path.join(path2GSAS2,'git_verinfo.py')
    try:
        fp = open(pyfile,'w')
    except:
        print(f'Creation of git version file {pyfile} failed')
        sys.exit()
    fp.write('# -*- coding: utf-8 -*-\n')
    fp.write(f'# {os.path.split(pyfile)[1]} - GSAS-II version info from git\n')
    fp.write(f'# Do not edit, generated by {" ".join(sys.argv)!r} script\n')
    fp.write(f'# Created {now}\n\n')
    fp.write(f'git_version = {commit0!r}\n')
    if tags0:
        fp.write(f'git_tags = {tags0}\n')
    else:
        fp.write('git_tags = []\n')
    fp.write(f'git_prevtaggedversion = {commitm1!r}\n')
    if tagsm1:
        fp.write(f'git_prevtags = {tagsm1}\n')
    else:
        fp.write(f'git_prevtags = []\n')
    fp.write(f'git_versiontag = {versiontag!r}\n')
    #
    fp.close()
    print(f'Created git version file {pyfile} at {now} for {commit0[:7]!r}')
