#!/bin/env python3

"""Checks the requirements.txt file for sorting.

Shows the differences (if any)
If called with -a applies the changes to the file
"""

import argparse
import difflib
import sys
from typing import Dict, List

req_file = 'requirements.txt'

parser = argparse.ArgumentParser(
    description=f'Checks and updates {req_file} sorting.'
)

parser.add_argument(
    '-c',
    '--check',
    action='store_true',
    help=('checks for sorting and shows the diff\
          returns rc=0 if all ok and rc=1 if there are differences')
)
parser.add_argument(
    '-u',
    '--update',
    action='store_true',
    help=f'update {req_file} with the sorted content'
)

args = parser.parse_args()

if not args.check and not args.update:
    parser.print_help()
    sys.exit(0)

data: str = ''
sorted_data: str = ''
diffs: str = ''
chunks: Dict[str, str] = {}
sorted_chunks: List[str]

try:
    with open(req_file, 'r', encoding='utf-8') as file:
        while True:
            line = file.readline()
            if not line:
                break
            s_line = line.strip()
            module, version = s_line.split('==')
            if not module or not version:
                raise ValueError(
                    'must be module==version'
                )
            data = f'{data}{line}'
            chunks[module] = version
except ValueError as err:
    print(f'Malformed file: {err}')

if not data:
    sys.exit(0)

sorted_chunks = sorted(chunks.keys(), key=str.casefold)

sorted_data = '\n'.join(
    [f'{sorted_data}{module}=={chunks[module]}' for module in sorted_chunks]
) + '\n'

if args.check:
    for line in difflib.unified_diff(data.splitlines(True),
                                     sorted_data.splitlines(True),
                                     fromfile=req_file,
                                     tofile=req_file):
        diffs = f'{diffs}{line}'

    if diffs:
        print(f"==> '{req_file}' has invalid sorting,",
              'please use tools/sort_requirements -cu to fix it.')
        print(diffs)

if diffs and args.update:
    with open(req_file, 'w', encoding='utf-8') as file:
        file.write(sorted_data)
    print(f"==> '{req_file}' is sorted.")
    sys.exit(0)

sys.exit(1 if diffs else 0)
