#!/usr/bin/env python

from __future__ import print_function

import argparse
import os
import re
import shutil

from changelog.git import stage_file
from changelog.util import load_unreleased_changes, marshall_release_changes, parse_version_string

VERSION_REGEX = re.compile('^[0-9]+\.[0-9]+\.[0-9]+$')
DATE_REGEX = re.compile('^[0-9]{4}-[0-9]{2}-[0-9]{2}$')

def validate_args(args):
    if not VERSION_REGEX.match(args.release_version):
        print("release-version is not in the correct format.")
    if not DATE_REGEX.match(args.release_date):
        print("release-date is not in the correct format.")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Finalize the unrelease changes in .changes/next-release")
    parser.add_argument('--release-version', '-v', dest='release_version', required=True, help="The version that the changes desrcribe. Must be in the form MAJOR.MINOR.PATCH")
    parser.add_argument('--release-date', '-d', dest='release_date', required=True, help="The date for the release, in ISO 8601 format (YYYY-MM-DD). Defaults to the current date.")
    parser.add_argument('--generate-changelog', '-g', dest='generate_changelog_now', action='store_true', help="Generate the change log now.")
    parser.add_argument('--dry-run', '-r', dest='dry_run', action='store_true', help="Whether it is a dry run to finalize the change log.")
    args = parser.parse_args()

    validate_args(args)

    next_release = load_unreleased_changes('.changes/next-release')
    if next_release is None:
        print("There are no unreleased changes.")
        exit(0)

    next_release.version = parse_version_string(args.release_version)
    next_release.date = args.release_date

    next_release_json = marshall_release_changes(next_release)

    filename = ".changes/%s.json" % next_release.version

    if os.path.isfile(filename):
        print("The file %s already exists!" % filename)
        exit(1)

    if args.dry_run:
        print("Dry run succeeded")
        exit(0)

    with open(filename, 'w') as f:
        f.write(next_release_json)

    shutil.rmtree('.changes/next-release')
    stage_file('.changes/')

    if args.generate_changelog_now:
        from changelog.writer import write_changelog
        write_changelog()
