#!/usr/bin/python3
# encoding=utf-8
#
# Copyright © 2017 Alexandre Detiste <alexandre@detiste.be>
# SPDX-License-Identifier: GPL-2.0-or-later

# Usage: _build/run-tool-uninstalled tools/check_gog.py

import json
import os
import subprocess

from debian.debian_support import Version

from game_data_packager.game import load_games
from game_data_packager.gog import GOG

yaml_files: dict[str, str] = {}
owned_games = GOG.owned_games()


def decode_filename(archive: str) -> tuple[str, str, str]:
    game = archive[len('setup_')::]
    game = game.rsplit('_', 1)[0].strip()
    version = archive.split('_')[-1][:-4:]
    return (archive, game, version)


print('# Reading data from YAML...')
for name, game in load_games(
    datadir=os.environ.get('GDP_BUILDDIR', 'out')
).items():
    game.load_file_data()
    has_tags = has_archive = is_removed = False
    for package in game.packages.values():
        gog = package.gog or game.gog
        if 'removed' in gog:
            is_removed = True
        elif 'url' in gog:
            has_tags = True
    for filename, f in game.files.items():
        if filename.startswith('setup_') and filename.endswith('.exe'):
            has_archive = True
            _, supported, version = decode_filename(filename)
            if '.' not in version:
                # ancient GOG packages
                continue
            if Version(version) > Version(yaml_files.get(supported, '0')):
                yaml_files[supported] = version
    if has_tags != has_archive and not is_removed:
        owned = game.gog_download_name(package) in owned_games
        print(('GOG metadata not in sync for %s. '
              + '(has_tags: %s, has_archive: %s, owned: %s)')
              % (name, has_tags, has_archive, owned))

print('# Reading data from LGOGDOWNLOADER...')
cache = os.path.expanduser('~/.cache/lgogdownloader/gamedetails.json')
if not os.path.isfile(cache):
    print("Couldn't locate any game, running 'lgogdownloader --login'")
    subprocess.call(['lgogdownloader', '--login'])
    print("... and now 'lgogdownloader --update-cache'")
    subprocess.call(['lgogdownloader', '--update-cache'])


def get_owned_files(cache: str) -> list[tuple[str, str, str]]:
    data = json.load(open(cache, encoding='utf-8'))
    owned_files: list[tuple[str, str, str]] = list()
    for game in data['games']:
        try:
            installers = game['installers']
        except KeyError:
            print('No installers for', game['gamename'])
            continue
        for installer in installers:
            filename = installer['path']
            filename = os.path.basename(filename)
            if filename.startswith('setup_') and filename.endswith('.exe'):
                owned_files.append(decode_filename(filename))
    return owned_files


owned_files = get_owned_files(cache)

print('# Left join...')
for supported, curr_ver in yaml_files.items():
    for _, to_match, last_ver in owned_files:
        if supported == to_match and last_ver > curr_ver:
            print("%-40s %12s -> %-12s" % (supported, curr_ver, last_ver))
