from hashids import Hashids

from ..config import settings

class ShortCodeEncoder:
    def __init__(self, salt=None, alphabet=None, min_length=6):
        self.salt = salt or settings.hashids_salt
        self.alphabet = alphabet or settings.encoder_alphabet

        self.hashids = Hashids(salt=self.salt, min_length=min_length, alphabet=self.alphabet)
        self.min_length = min_length

    def encode(self, url_id: int) -> str:
        return self.hashids.encode(url_id)

    def decode(self, shortcode: str) -> int:
        decoded = self.hashids.decode(shortcode)
        return decoded[0] if decoded else None

    def is_valid(self, shortcode: str) -> bool:
        if len(shortcode) < self.min_length:
            return False
        if any(char not in self.alphabet for char in shortcode):
            return False
        return True

# Singleton instance of encoder
encoder = ShortCodeEncoder()
