#!/usr/bin/python3
# encoding=utf-8
# Copyright 2024 Simon McVittie
# SPDX-License-Identifier: FSFAP

import os
import sys
import unittest
from pathlib import Path
from typing import Any


TOP_SRCDIR = Path(__file__).resolve().parent.parent


if 'GDP_UNINSTALLED' in os.environ:
    sys.path.insert(0, str(TOP_SRCDIR))
else:
    sys.path.insert(0, '/usr/share/game-data-packager')
    sys.path.insert(0, '/usr/share/games/game-data-packager')


class AssertVersionMatches(unittest.TestCase):
    def setUp(self) -> None:
        pass

    def test_version_number(self) -> None:
        from game_data_packager.version import (
            GAME_PACKAGE_VERSION,
            GAME_PACKAGE_RELEASE,
        )

        contents: dict[str, Any] = {}

        if 'GDP_BUILDDIR' in os.environ:
            TOP_BUILDDIR = Path(os.environ['GDP_BUILDDIR']).resolve()
            with open(TOP_BUILDDIR / 'version.py') as reader:
                exec(reader.read(), contents, contents)

        try:
            from debian.changelog import Changelog
        except ImportError as e:
            self.skipTest(str(e))

        with open(TOP_SRCDIR / 'debian' / 'changelog') as reader:
            changelog = Changelog(reader, max_blocks=1)

        print(f'# version in debian/changelog: {changelog.version!r}')
        print(f'# dists in debian/changelog: {changelog.distributions!r}')
        print(f'# version from build system: {GAME_PACKAGE_VERSION!r}')
        print(f'# revision from build system: {GAME_PACKAGE_RELEASE!r}')

        if 'UNRELEASED' in changelog.distributions:
            self.skipTest('package not yet released')

        if '~' in str(changelog.version) or '+' in str(changelog.version):
            self.skipTest(
                "version number has ~ or +, assuming you know what "
                "you're doing"
            )

        if 'ubuntu' in str(changelog.version):
            self.skipTest("this test is skipped on Ubuntu and derivatives")

        self.assertEqual(
            changelog.upstream_version,
            GAME_PACKAGE_VERSION,
        )
        self.assertEqual(
            changelog.debian_revision or '',
            GAME_PACKAGE_RELEASE,
        )

        if 'GDP_BUILDDIR' in os.environ:
            GAME_PACKAGE_VERSION = contents['GAME_PACKAGE_VERSION']
            GAME_PACKAGE_RELEASE = contents['GAME_PACKAGE_RELEASE']

            print(f'# version from built files: {GAME_PACKAGE_VERSION!r}')
            print(f'# revision from built files: {GAME_PACKAGE_RELEASE!r}')

            self.assertEqual(
                changelog.upstream_version,
                GAME_PACKAGE_VERSION,
            )
            self.assertEqual(
                changelog.debian_revision or '',
                GAME_PACKAGE_RELEASE,
            )

    def tearDown(self) -> None:
        pass


if __name__ == '__main__':
    from gdp_test_common import main
    main()
