import argparse
import subprocess
import toml

# Create the parser
parser = argparse.ArgumentParser(description='Generate pyproject.toml file.')
parser.add_argument('Path', metavar='path', type=str, help='the path to the pyproject.toml.in file')

# Parse the arguments
args = parser.parse_args()

# Get the latest tag from git
tag = subprocess.getoutput('git describe --abbrev=4 --dirty --always')

# Load the pyproject.toml file
with open(args.Path, 'r') as file:
    pyproject = toml.load(file)

# Update the version
if 'tool' in pyproject and 'poetry' in pyproject['tool'] and 'version' in pyproject['tool']['poetry']:
    pyproject['tool']['poetry']['version'] = tag

with open('pyproject.toml', 'w') as file:
    file.write("# This file is generated by scripts/generate-pyproject.py.\n")
    file.write("# Do not change it by hand, instead modify pyproject.toml.in.\n")
    file.write("# Create a tag using: git tag -a 0.0.10\n")
    file.write("# This tag will be used as a version in the pyproject.toml.\n")

# Write the pyproject.toml file
with open('pyproject.toml', 'a') as file:
    toml.dump(pyproject, file)