#!/usr/bin/env python
# coding: utf-8

# Copyright (c) Mito.
# Distributed under the terms of the Modified BSD License.

"""
Contains utilities for bumping the version of a Mito project, across
all the files where it needs to be bumped. 
"""

import json
from typing import Tuple

def get_package_version() -> Tuple[int, int, int]:
    with open('package.json') as f:
        str_version =  json.loads(f.read())['version']

    return tuple(map(int, str_version.split('.')))

def get_next_version() -> Tuple[int, int, int]:
    (x, y, z) = get_package_version()
    return (x, y, z + 1)

def bump_version(new_version: Tuple[int, int, int]=None):
    """
    Bumps the version of the Mito project to the next minor logical version.

    If a new_version is given, then will bump to that version specificially. new_version
    should be a tuple of the form (x, y, z).
    """

    if new_version is None:
        new_version = get_next_version()

    # Open mitosheet/_version.py, and replace the version
    with open('mitosheet/_version.py', 'r+') as py_verson:
        py_version_contents = py_verson.read()
        """
        The file has the format:

        # AUTOGENERATED | DO NOT EDIT BELOW
        version_info = (x, y, z)
        # AUTOGENERATED | DO NOT EDIT ABOVE
        """
        AUTOGENERATED_START = '# AUTOGENERATED | DO NOT EDIT BELOW\n'
        AUTOGENERATED_END = '# AUTOGENERATED | DO NOT EDIT ABOVE\n'

        start = py_version_contents.find(AUTOGENERATED_START)
        end = py_version_contents.find(AUTOGENERATED_END) + len(AUTOGENERATED_END)

        next_version_info = f'version_info = {new_version}\n'
        new_contents = py_version_contents[:start] + AUTOGENERATED_START + next_version_info + AUTOGENERATED_END + py_version_contents[end:]

        # Go back to start of file, to write
        py_verson.seek(0)
        py_verson.write(new_contents)    
    
    # Then, update it in package.json
    with open('package.json', 'r+') as f:
        package_obj = json.loads(f.read())
        package_obj['version'] = '.'.join(map(str, new_version))

        # Rewind to start of file, to write
        f.seek(0)
        f.write(json.dumps(package_obj, indent=2))

    print('Bump Mito version to ', new_version)

if __name__ == '__main__':
    bump_version()