import argparse
import toml
import os
import re
import logging

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


def update_pyproject(version):
    try:
        with open('pyproject.toml', 'r') as f:
            pyproject = toml.load(f)

        pyproject['tool']['poetry']['version'] = version

        with open('pyproject.toml', 'w') as f:
            toml.dump(pyproject, f)
        logging.info('Updated pyproject.toml with version %s', version)
    except FileNotFoundError:
        logging.error('pyproject.toml not found')
    except Exception as e:
        logging.error('Error updating pyproject.toml: %s', str(e))


def update_gitlab_ci(version):
    gitlab_ci_path = '.gitlab-ci.yml'

    if os.path.exists(gitlab_ci_path):
        try:
            with open(gitlab_ci_path, 'r') as f:
                gitlab_ci = f.readlines()

            updated_gitlab_ci = []
            tag_updated = False

            for line in gitlab_ci:
                if line.strip().startswith('GIT_TAG:'):
                    updated_gitlab_ci.append(f'  GIT_TAG: "{version}"\n')
                    tag_updated = True
                else:
                    updated_gitlab_ci.append(line)

            if not tag_updated:
                updated_gitlab_ci.append(f'  GIT_TAG: "{version}"\n')

            with open(gitlab_ci_path, 'w') as f:
                f.writelines(updated_gitlab_ci)
            logging.info('Updated .gitlab-ci.yml with GIT_TAG %s', version)
        except Exception as e:
            logging.error('Error updating .gitlab-ci.yml: %s', str(e))
    else:
        logging.warning('%s not found', gitlab_ci_path)


def update_version_in_file(file_path, pattern, replacement):
    if os.path.exists(file_path):
        try:
            with open(file_path, 'r') as f:
                content = f.read()

            updated_content = re.sub(pattern, replacement, content)

            with open(file_path, 'w') as f:
                f.write(updated_content)
            logging.info('Updated %s with version %s', file_path, replacement)
        except Exception as e:
            logging.error('Error updating %s: %s', file_path, str(e))
    else:
        logging.warning('%s not found', file_path)


def update_desktop_entry(version):
    desktop_file_path = 'debian/rocket.desktop'
    if os.path.exists(desktop_file_path):
        try:
            with open(desktop_file_path, 'r') as f:
                content = f.read()

            pattern = r'Exec=/usr/bin/rocket_\d+\.\d+\.\d+'
            replacement = f'Exec=/usr/bin/rocket_{version}'
            updated_content = re.sub(pattern, replacement, content)

            with open(desktop_file_path, 'w') as f:
                f.write(updated_content)
            logging.info('Updated %s with version %s', desktop_file_path, replacement)
        except Exception as e:
            logging.error('Error updating %s: %s', desktop_file_path, str(e))
    else:
        logging.warning('%s not found', desktop_file_path)


def main():
    parser = argparse.ArgumentParser(description='Update project version')
    parser.add_argument('--version', required=True, help='Update the Rocket version throughout the entire project')
    args = parser.parse_args()
    new_version = args.version

    update_pyproject(new_version)
    update_gitlab_ci(new_version)
    update_version_in_file('src/views/info_dialog.py', r'Version [\d.]+', f'Version {new_version}')
    update_version_in_file('README.md', r'Rocket v[\d.]+', f'Rocket v{new_version}')
    update_desktop_entry(new_version)


if __name__ == '__main__':
    main()
