# Copyright 2022 The Debusine Developers
# See the AUTHORS file at the top-level directory of this distribution
#
# This file is part of Debusine. It is subject to the license terms
# in the LICENSE file found in the top-level directory of this
# distribution. No part of Debusine, including this file, may be copied,
# modified, propagated, or distributed except according to the terms
# contained in the LICENSE file.

"""Tests for utils module."""

import hashlib
from pathlib import Path
from unittest import TestCase, mock

from debian import deb822

from debusine.test import TestHelpersMixin
from debusine.utils import (
    CALCULATE_HASH_CHUNK_SIZE,
    calculate_hash,
    find_file_suffixes,
    find_files_suffixes,
    is_command_available,
    parse_content_range_header,
    parse_range_header,
    read_changes,
    read_dsc,
)


class UtilsTests(TestHelpersMixin, TestCase):
    """Tests for the utils functions."""

    def test_calculate_hash_small_file(self):
        """calculate_hash return the correct sha256 for the file."""
        contents = b"debusine"
        sha256_expected = hashlib.sha256(contents).digest()

        temporary_file = self.create_temporary_file(contents=contents)

        self.assertEqual(
            calculate_hash(Path(temporary_file), "sha256"),
            sha256_expected,
        )

    def test_calculate_hash_big_file(self):
        """
        calculate_hash return the correct sha256 for a big file.

        A big file is a file bigger than CALCULATE_HASH_CHUNK_SIZE.
        """
        size_to_write = int(CALCULATE_HASH_CHUNK_SIZE * 2.5)

        contents = bytearray(size_to_write)

        temporary_file = self.create_temporary_file(contents=contents)

        self.assertEqual(
            calculate_hash(Path(temporary_file), "sha256"),
            hashlib.sha256(contents).digest(),
        )

    def test_parse_range_header_no_header(self):
        """parse_range_header return None: no "Range" header."""
        self.assertIsNone(parse_range_header({}))

    def test_parse_range_header_invalid_header(self):
        """parse_range_header raise ValueError: invalid header."""
        invalid_header = "invalid-header"
        error = f'Invalid Range header: "{invalid_header}"'
        with self.assertRaisesRegex(ValueError, error):
            parse_range_header({"Range": invalid_header})

    def test_parse_range_header(self):
        """parse_range_header return dictionary with start and end."""
        start = 10
        end = 24
        range_header = f"bytes={start}-{end}"
        headers = {"Range": range_header}

        self.assertEqual(
            parse_range_header(headers), {"start": start, "end": end}
        )

    def test_parse_content_range_header_no_header(self):
        """parse_content_range_header return None: no "Content-Range"."""
        self.assertIsNone(parse_content_range_header({}))

    def test_parse_content_range_header_start_end_size(self):
        """parse_content_range_header return dict with integers."""
        params = [
            {
                "header": "bytes 10-20/30",
                "expected": {"start": 10, "end": 20, "size": 30},
            },
            {
                "header": "bytes 10-20/*",
                "expected": {"start": 10, "end": 20, "size": "*"},
            },
            {
                "header": "bytes */30",
                "expected": {"start": "*", "end": None, "size": 30},
            },
            {
                "header": "bytes */*",
                "expected": {"start": "*", "end": None, "size": "*"},
            },
        ]

        for param in params:
            with self.subTest(param):
                headers = {"Content-Range": param["header"]}

                self.assertEqual(
                    parse_content_range_header(headers), param["expected"]
                )

    def test_parse_content_range_header_invalid_header(self):
        """parse_content_range_header raise ValueError: invalid header."""
        invalid_header = "invalid-header"
        error = f'Invalid Content-Range header: "{invalid_header}"'
        with self.assertRaisesRegex(ValueError, error):
            parse_content_range_header({"Content-Range": invalid_header})

    def test_read_dsc_file(self):
        """_read_dsc return a deb822.Dsc object: it was a valid Dsc file."""
        dsc_file = self.create_temporary_file()
        self.write_dsc_example_file(dsc_file)

        dsc = read_dsc(dsc_file)

        self.assertIsInstance(dsc, deb822.Dsc)

    def test_read_dsc_file_invalid(self):
        """_read_dsc return None: it was a not a valid Dsc file."""
        dsc_file = self.create_temporary_file(contents=b"invalid dsc file")

        dsc = read_dsc(dsc_file)

        self.assertIsNone(dsc)

    def test_read_changes_file(self):
        """read_changes returns deb822.Changes for a valid .changes file."""
        build_directory = self.create_temporary_directory()
        changes_file = build_directory / "foo.changes"
        self.write_changes_file(changes_file, [])

        changes = read_changes(build_directory)

        self.assertIsInstance(changes, deb822.Changes)

    def test_read_changes_file_missing(self):
        """read_changes returns None if the directory has no .changes file."""
        build_directory = self.create_temporary_directory()

        changes = read_changes(build_directory)

        self.assertIsNone(changes)

    def test_find_file_suffixes_multiple_files(self):
        """find_file_suffixes() return two files with different suffixes."""
        temporary_directory = self.create_temporary_directory()

        # Add a deb file
        (deb := temporary_directory / "file.deb").write_text("deb")

        # Add a udeb file
        (udeb := temporary_directory / "file.udeb").write_text("deb")

        # Add a file that is not returned
        (temporary_directory / "README.txt").write_text("README")

        # Check deb and udeb files
        self.assertEqual(
            find_files_suffixes(temporary_directory, [".deb", ".udeb"]),
            sorted([deb, udeb]),
        )

    def test_find_file_suffix_raise_runtime_error(self):
        """find_file() raise RuntimeError: two possible log files."""
        temporary_directory = self.create_temporary_directory()

        suffix = "build"

        (file1 := temporary_directory / f"log1.{suffix}").write_text("Log1")
        (file2 := temporary_directory / f"log2.{suffix}").write_text("Log2")

        files = sorted([str(file1), str(file2)])

        # assertRaisesRegex must have the chars [] escaped
        files = str(files).replace("[", "").replace("]", "")

        with self.assertRaisesRegex(
            RuntimeError, rf"^More than one \['{suffix}'\] file: \[{files}\]$"
        ):
            find_file_suffixes(temporary_directory, [suffix])

    def test_find_files_suffix(self):
        """find_files_suffix() return multiple files."""
        temporary_directory = self.create_temporary_directory()

        # Create two files to be returned
        (deb1_file := temporary_directory / "hello.deb").write_text("First")
        (deb2_file := temporary_directory / "hello-2.deb").write_text("Second")

        # Create a non-relevant file
        (temporary_directory / "README.txt").write_text("a test")

        # Create a file that could match (*.deb) but is a symbolic link
        (temporary_directory / "temp.deb").symlink_to(deb1_file)

        # Create a file that could match (*.deb) but is a directory
        (temporary_directory / "debian.deb").mkdir()

        self.assertEqual(
            find_files_suffixes(temporary_directory, [".deb"]),
            sorted([deb1_file, deb2_file]),
        )

    def test_find_files_suffix_include_symbolic_links(self):
        """
        find_files_suffix() return files including symbolic links.

        The option include_symlinks is True.
        """
        temporary_directory = self.create_temporary_directory()

        # Create one file and one symbolic link to the file
        file_name = "file.txt"
        symbolic_link_name = "symbolic.txt"
        (file := temporary_directory / file_name).write_text("test")
        (symbolic_link := temporary_directory / symbolic_link_name).symlink_to(
            file
        )

        self.assertEqual(
            find_files_suffixes(
                temporary_directory, [".txt"], include_symlinks=True
            ),
            [file, symbolic_link],
        )

    def test_find_file_suffixes_one_file(self):
        """find_file_suffixes() return the expected file."""
        temporary_directory = self.create_temporary_directory()

        # Add a log file
        (log_file := temporary_directory / "log.build").write_text("log")

        # Add a file that is not returned
        (temporary_directory / "README.txt").write_text("README")

        # Check return the correct log file
        self.assertEqual(
            find_file_suffixes(temporary_directory, [".build"]),
            log_file,
        )

    def patch_shutil_which(self, available: bool) -> None:
        """Patch shutil.which to respond either positively or negatively."""
        patcher = mock.patch(
            "shutil.which", return_value="/usr/bin/test" if available else None
        )
        patcher.start()
        self.addCleanup(patcher.stop)

    def test_is_command_available_yes(self):
        """is_command_available returns True if the command exists."""
        self.patch_shutil_which(True)
        self.assertTrue(is_command_available("test"))

    def test_is_command_available_no(self):
        """is_command_available returns False if the command does not exist."""
        self.patch_shutil_which(False)
        self.assertFalse(is_command_available("test"))
