            
import redis
from typing import List, Tuple
import random
RAND_TAG_LIST = [
    'acoustic',
    'aggressive',
    'anthemic',
    'atmospheric',
    'bouncy',
    'chill',
    'dark',
    'dreamy',
    'electronic',
    'emotional',
    'epic',
    'experimental',
    'futuristic',
    'groovy',
    'heartfelt',
    'infectious',
    'melodic',
    'mellow',
    'powerful',
     'psychedelic',
    'romantic',
    'smooth',
    'syncopated',
    'uplifting',
    'afrobeat',
    'anime',
    'ballad',
    'bedroom pop',
    'bluegrass',
    'blues',
    'classical',
    'country',
    'cumbia',
    'dance',
    'delta blues',
    'electropop',
    'disco',
    'drum and bass',
    'edm',
    'emo',
    'folk',
    'funk',
    'future bass',
    'gospel',
    'grunge',
    'grime',
    'hip hop',
    'house',
    'indie',
    'j-pop',
    'jazz',
    'k-pop',
    'kids music',
    'metal',
    'new jack swing',
    'new wave',
    'opera',
    'punk',
    'raga',
    'rap',
    'reggae',
    'reggaeton',
    'rock',
    'rumba',
    'salsa',
    'samba',
    'sertanejo',
    'soul',
    'synthpop',
    'swing',
     'synthwave',
     'techno',
     'trap',
     'uk garage'
];

class RedisTagManager:
    def __init__(self, host="localhost", port=6379, db=0):
        self.redis_client = redis.Redis(
            host=host, port=port, db=db, decode_responses=True
        )
    def get_all_tags(self):
        tags = {}
        cursor = 0
        while True:
            cursor, keys = self.redis_client.scan(cursor=cursor, match="*", count=1000)
            for key in keys:
                try:
                    votes = int(self.redis_client.get(key) or 0)
                    tags[key.decode() if isinstance(key, bytes) else key] = votes
                except (ValueError, TypeError):
                    continue
            if cursor == 0:
                break
        return tags
    def get_top_tags(self, n: int) -> List[Tuple[str, int]]:
        """Get the top N tags sorted by vote count."""
        tags = self.get_all_tags()
        # Sort by vote count descending
        sorted_tags = sorted(tags.items(), key=lambda x: x[1], reverse=True)
        if len(sorted_tags) == 0:
            return [(tag, 0) for tag in random.sample(RAND_TAG_LIST, n)]
        if len(sorted_tags) < n:
            print(f"********* sorted_tags: {sorted_tags} *********")
            return sorted_tags
        return sorted_tags[:n]
    def get_and_reset_tags(self, n: int) -> List[str]:
        """Get top N tags and clear the entire database."""
        top_tags = self.get_top_tags(n)
        tag_names = [tag[0] for tag in top_tags]
        self.redis_client.flushdb()
        return tag_names
