# SPDX-FileCopyrightText: (c) TagStudio Contributors
# SPDX-License-Identifier: GPL-3.0-only


from collections.abc import Iterator
from dataclasses import dataclass, field

import structlog

from tagstudio.core.library.alchemy.library import Library
from tagstudio.core.library.alchemy.models import Entry
from tagstudio.core.library.ignore import Ignore

logger = structlog.get_logger(__name__)


@dataclass
class IgnoredRegistry:
    """State tracker for ignored entries."""

    lib: Library
    ignored_entries: list[Entry] = field(default_factory=list)

    @property
    def ignored_count(self) -> int:
        return len(self.ignored_entries)

    def reset(self):
        self.ignored_entries.clear()

    def refresh_ignored_entries(self) -> Iterator[int]:
        """Track the number of entries that would otherwise be ignored by the current rules."""
        logger.info("[IgnoredRegistry] Refreshing ignored entries...")

        self.ignored_entries = []

        for i, entry in enumerate(self.lib.all_entries()):
            yield i
            if not Ignore.compiled_patterns:
                # If the compiled_patterns has malfunctioned, don't consider that a false positive
                yield i
            elif Ignore.compiled_patterns.match(entry.path):
                self.ignored_entries.append(entry)

    def remove_ignored_entries(self) -> None:
        self.lib.remove_entries(list(map(lambda ignored: ignored.id, self.ignored_entries)))
        self.ignored_entries = []
