import logging

import allure
import pytest
from frostfs_testlib import reporter
from frostfs_testlib.resources.error_patterns import OBJECT_NOT_FOUND
from frostfs_testlib.steps.cli.container import create_container
from frostfs_testlib.steps.cli.object import get_object_from_random_node, head_object, put_object_to_random_node
from frostfs_testlib.steps.epoch import get_epoch
from frostfs_testlib.storage.dataclasses.object_size import ObjectSize
from frostfs_testlib.testing.cluster_test_base import ClusterTestBase
from frostfs_testlib.utils.file_utils import generate_file, get_file_hash

from pytest_tests.helpers.utility import wait_for_gc_pass_on_storage_nodes

logger = logging.getLogger("NeoLogger")


@pytest.mark.sanity
@pytest.mark.grpc_api
class TestObjectApiLifetime(ClusterTestBase):
    @allure.title("Object is removed when lifetime expired (obj_size={object_size})")
    def test_object_api_lifetime(self, default_wallet: str, object_size: ObjectSize):
        """
        Test object deleted after expiration epoch.
        """

        wallet = default_wallet
        endpoint = self.cluster.default_rpc_endpoint
        cid = create_container(wallet, self.shell, endpoint)

        file_path = generate_file(object_size.value)
        file_hash = get_file_hash(file_path)
        epoch = get_epoch(self.shell, self.cluster)

        oid = put_object_to_random_node(wallet, file_path, cid, self.shell, self.cluster, expire_at=epoch + 1)
        got_file = get_object_from_random_node(wallet, cid, oid, self.shell, self.cluster)
        assert get_file_hash(got_file) == file_hash

        with reporter.step("Tick two epochs"):
            for _ in range(2):
                self.tick_epoch()

        # Wait for GC, because object with expiration is counted as alive until GC removes it
        wait_for_gc_pass_on_storage_nodes()

        with reporter.step("Check object deleted because it expires on epoch"):
            with pytest.raises(Exception, match=OBJECT_NOT_FOUND):
                head_object(wallet, cid, oid, self.shell, self.cluster.default_rpc_endpoint)
            with pytest.raises(Exception, match=OBJECT_NOT_FOUND):
                get_object_from_random_node(wallet, cid, oid, self.shell, self.cluster)

        with reporter.step("Tick additional epoch"):
            self.tick_epoch()

        wait_for_gc_pass_on_storage_nodes()

        with reporter.step("Check object deleted because it expires on previous epoch"):
            with pytest.raises(Exception, match=OBJECT_NOT_FOUND):
                head_object(wallet, cid, oid, self.shell, self.cluster.default_rpc_endpoint)
            with pytest.raises(Exception, match=OBJECT_NOT_FOUND):
                get_object_from_random_node(wallet, cid, oid, self.shell, self.cluster)