
import time
import threading
import os
import random
import os
import queue
import threading
import asyncio
import time
import pygame
from extend import extend, poll_for_mp3
from redis_manager import RedisTagManager
REDIS_HOST = "localhost"
REDIS_PORT = 6379
REDIS_DB = 1


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'
];

tag_manager = RedisTagManager(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)

def read_tags(n=1):
    # return ["Lo-fi production Aggressive vocals Distorted guitars Fast tempos Minimalist melody Power chords Chromatic riffs Tritone use Punk-influenced drums Raw energy Proto-thrash Occult themes DIY aesthetic Bass distortion Atonal vocals Repetitive riffs"]
    # tags = tag_manager.get_and_reset_tags(5)
    # print(f"********* next tags: {tags} *********")
    return " ".join(random.sample(RAND_TAG_LIST, n))

# Initialize mixer
pygame.mixer.init()

# Queue to hold MP3 file paths
song_queue = queue.Queue()

def player():
    """Plays the first 90 seconds of each queued MP3 file."""
    while True:
        song_path = song_queue.get()
        if not os.path.isfile(song_path):
            print(f"File not found: {song_path}")
            continue

        try:
            pygame.mixer.music.load(song_path)
            pygame.mixer.music.play()
            print(f"Now playing first 90 seconds of: {song_path}")

            start_time = time.time()
            while pygame.mixer.music.get_busy():
                if time.time() -     start_time > 90:
                    pygame.mixer.music.stop()
                    print("Stopped after 90 seconds.")
                    break
                time.sleep(0.5)

        except Exception as e:
            print(f"Playback error: {e}")


if __name__ == "__main__":
    STARTER_CLIP_ID = "c7a77f50-9bcb-43d7-b0a3-acf9bbc25907"
    STARTER_CLIP_TAGS = "techno pop upbeat"
    starter_clip_file = asyncio.run(poll_for_mp3(f"https://cdn1.suno.ai/{STARTER_CLIP_ID}.mp3"))
    class StarterClip:
        def __init__(self):
            self.id = "starter_clip"
            self.s3_id = STARTER_CLIP_ID
            self.metadata = {
                "prompt":"",
                "history": [],
                "type": "gen",
                "duration": 120.0,
                "tags": STARTER_CLIP_TAGS,
                "make_instrumental": 1,
            }
    song_queue.put(starter_clip_file)
    def clip_generator():
        continue_clip = StarterClip()
        
        def prepare_next_song(tags, neg_tags, clip):
            next_song_file, s3_id = extend(tags, neg_tags, clip)
            song_queue.put(next_song_file)
            return s3_id
        neg_tags = STARTER_CLIP_TAGS
        while True:
            tags = read_tags()
            print(f"********* next tags: {tags} *********")
            s3_id = prepare_next_song(tags, neg_tags,continue_clip)
            neg_tags = tags
            continue_clip.s3_id = s3_id
            continue_clip.metadata["tags"] = " ".join(tags)
            continue_clip.metadata["prompt"] = " ".join(tags)
    threading.Thread(target=clip_generator, daemon=True).start()
    player()
   