"""Paket, Start-Skript, Menü-Eintrag und Stockfish-Download (ohne Netz)."""

import glob
import io
import os
import tarfile
import tempfile
import tomllib
import unittest
import zipfile
from unittest import mock

from schach import desktop, stockfish

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


class PyprojectTest(unittest.TestCase):
    def setUp(self):
        with open(os.path.join(ROOT, "pyproject.toml"), "rb") as fh:
            self.project = tomllib.load(fh)

    def test_all_data_files_are_packaged(self):
        """Jede Nicht-Python-Datei unter schach/ muss ein package-data-Muster treffen."""
        package = os.path.join(ROOT, "schach")
        patterns = self.project["tool"]["setuptools"]["package-data"]["schach"]
        packaged = set()
        for pattern in patterns:
            packaged |= {os.path.normpath(p) for p in glob.glob(os.path.join(package, pattern), recursive=True)
                         if os.path.isfile(p)}
        missing = []
        for folder, dirs, files in os.walk(package):
            dirs[:] = [d for d in dirs if d != "__pycache__"]
            missing += [os.path.relpath(os.path.join(folder, f), package) for f in files
                        if not f.endswith(".py") and os.path.normpath(os.path.join(folder, f)) not in packaged]
        self.assertEqual(missing, [])

    def test_gui_script_points_to_main(self):
        target = self.project["project"]["gui-scripts"]["schach"]
        module, func = target.split(":")
        self.assertEqual((module, func), ("schach.__main__", "main"))
        from schach import __main__
        self.assertTrue(callable(__main__.main))

    def test_webgpu_is_a_dependency(self):
        deps = " ".join(self.project["project"]["dependencies"])
        self.assertIn("onnxruntime>=", deps)
        self.assertIn("onnxruntime-ep-webgpu", deps)


class StockfishTest(unittest.TestCase):
    def test_build_per_platform(self):
        self.assertEqual(stockfish.build("linux", "x86_64")[0], "stockfish-linux-x86-64-universal.tar.gz")
        self.assertEqual(stockfish.build("linux", "arm64")[0], "stockfish-linux-arm64-universal.tar.gz")
        self.assertEqual(stockfish.build("win32", "AMD64")[0], "stockfish-windows-x86-64-universal.zip")
        self.assertEqual(stockfish.build("darwin", "arm64")[0], "stockfish-macos-universal.tar.gz")
        self.assertIsNone(stockfish.build("linux", "mips"))

    def test_checksums_look_like_sha256(self):
        for archive, sha in stockfish.BUILDS.values():
            self.assertRegex(sha, r"^[0-9a-f]{64}$", archive)

    def test_binary_path(self):
        self.assertTrue(stockfish.binary_path("stockfish-windows-x86-64-universal.zip", "/c")
                        .endswith(os.path.join("stockfish-sf_19", "stockfish-windows-x86-64-universal.exe")))

    def test_env_wins(self):
        with mock.patch.dict(os.environ, {"SCHACH_STOCKFISH": "/opt/sf"}):
            self.assertEqual(stockfish.command(), (["/opt/sf"], None))

    def test_without_system_stockfish_it_prepares(self):
        with mock.patch.dict(os.environ, {}, clear=False), mock.patch("shutil.which", return_value=None):
            os.environ.pop("SCHACH_STOCKFISH", None)
            self.assertEqual(stockfish.command(), ([], stockfish.prepare))

    def _archive(self, folder, kind, name):
        body, licence = b"#!/bin/sh\necho stockfish\n", b"GPL"
        path = os.path.join(folder, "sf." + kind)
        if kind == "zip":
            with zipfile.ZipFile(path, "w") as zf:
                zf.writestr(f"stockfish/{name}", body)
                zf.writestr("stockfish/Copying.txt", licence)
                zf.writestr("stockfish/wiki/Home.md", b"x")
        else:
            with tarfile.open(path, "w:gz") as tf:
                for member, data in ((f"stockfish/{name}", body), ("stockfish/Copying.txt", licence),
                                     ("../boese", b"x")):
                    info = tarfile.TarInfo(member)
                    info.size = len(data)
                    tf.addfile(info, io.BytesIO(data))
        return path

    def test_extract_only_program_and_licence(self):
        for kind in ("tar.gz", "zip"):
            with self.subTest(kind=kind), tempfile.TemporaryDirectory() as tmp:
                out = os.path.join(tmp, "out")
                os.makedirs(out)
                stockfish.extract(self._archive(tmp, kind, "sf-bin"), out, "sf-bin")
                self.assertEqual(sorted(os.listdir(out)), ["COPYING.txt", "sf-bin"])
                self.assertTrue(os.access(os.path.join(out, "sf-bin"), os.X_OK))
                self.assertFalse(os.path.exists(os.path.join(tmp, "boese")))

    def test_prepare_downloads_once(self):
        with tempfile.TemporaryDirectory() as tmp:
            archive, _ = stockfish.build("linux", "x86_64")
            name = archive.removesuffix(".tar.gz")

            def fake_download(url, target, sha256, progress=None, what=""):
                self.assertTrue(url.endswith(archive))
                os.makedirs(os.path.dirname(target), exist_ok=True)  # wie das echte download()
                os.replace(self._archive(tmp, "tar.gz", name), target)

            with mock.patch.object(stockfish, "build", return_value=(archive, "0" * 64)), \
                 mock.patch.object(stockfish, "download", side_effect=fake_download) as dl:
                first = stockfish.prepare(base=tmp)
                second = stockfish.prepare(base=tmp)
            self.assertEqual(first, second)
            self.assertEqual(dl.call_count, 1)
            self.assertTrue(os.path.isfile(first[0]))
            self.assertFalse(os.path.exists(os.path.join(os.path.dirname(first[0]), archive)))

    def test_unknown_platform_explains(self):
        with mock.patch.object(stockfish, "build", return_value=None):
            with self.assertRaisesRegex(FileNotFoundError, "Stockfish installieren"):
                stockfish.prepare()


class DesktopTest(unittest.TestCase):
    def test_script_is_used_with_full_path(self):
        with tempfile.TemporaryDirectory() as tmp:
            script = os.path.join(tmp, "schach")
            with open(script, "w") as fh:
                fh.write("#!/bin/sh\n")
            os.chmod(script, 0o755)
            self.assertEqual(desktop.launch_command(script), (script, None))

    def test_python_m_uses_project_folder(self):
        exec_line, workdir = desktop.launch_command("/irgendwo/schach/__main__.py")
        self.assertTrue(exec_line.endswith(" -m schach"))
        self.assertEqual(workdir, ROOT)

    def test_quote(self):
        self.assertEqual(desktop._quote("/usr/bin/schach"), "/usr/bin/schach")
        self.assertEqual(desktop._quote("/home/a b/schach"), '"/home/a b/schach"')
        self.assertEqual(desktop._quote('/x/"$y'), '"/x/\\"\\$y"')

    def test_install_and_uninstall(self):
        with tempfile.TemporaryDirectory() as tmp:
            entry, icon = desktop.install(base=tmp, argv0="/irgendwo/__main__.py")
            with open(entry, encoding="utf-8") as fh:
                text = fh.read()
            self.assertIn("Icon=app.schach.Schach\n", text)
            self.assertIn("StartupWMClass=app.schach.Schach\n", text)
            self.assertIn(f"Path={ROOT}\n", text)
            self.assertTrue(os.path.isfile(icon))
            self.assertEqual(sorted(desktop.uninstall(base=tmp)), sorted([entry, icon]))

    def test_icon_is_svg(self):
        with open(desktop.ICON, encoding="utf-8") as fh:
            self.assertIn("<svg", fh.read(200))


class DownloadStatusTest(unittest.TestCase):
    def test_subtitle_lists_running_downloads(self):
        from schach.app import SchachApp

        class Stub:
            maia_status = ""
            downloads = {"Maia": (78_000_000, 156_000_000), "Stockfish": (8_000_000, None)}
            get_windows = staticmethod(list)

        stub = Stub()
        SchachApp._show_downloads(stub)
        self.assertEqual(stub.maia_status,
                         "Einmaliger Download: Maia 50 % · 78 von 156 MB – Stockfish 8 MB")
        stub.downloads = {}
        SchachApp._show_downloads(stub)
        self.assertEqual(stub.maia_status, "Maia wird geladen …")


if __name__ == "__main__":
    unittest.main()
