import threading
from typing import List, Optional

from pydantic import BaseModel

MAX_AMBIGUOUS = 5


class AtomicKwMatch:
    def __init__(self, matches: Optional[List[str]] = None, score: int = 0):
        self._score = score
        self._matches = matches if matches is not None else []
        self._lock = threading.Lock()

    def get_score(self) -> int:
        return self._score

    def get_matches(self) -> List[str]:
        return self._matches

    def get_matches_size(self) -> int:
        return len(self._matches)

    def get_first_match(self) -> Optional[str]:
        return self._matches[0] if self._matches else None

    def set(self, match: str, score: int):
        if score <= 0:
            return

        with self._lock:
            if score > self._score:
                self._matches = [match]
                self._score = score
            elif score == self._score and self.get_matches_size() < MAX_AMBIGUOUS:
                self._matches.append(match)
