import telebot
import os
import datetime
import subprocess
import requests
from bs4 import BeautifulSoup
import re

# Replace 'YOUR_API_TOKEN' with your actual Telegram Bot API token
bot = telebot.TeleBot("TOKEN")
dldir = "/path/to/Music/"
workingdir = "/path/to/script"

print("tg_spotdl bot is running.")

@bot.message_handler(commands=['start'])
def start(message):
    bot.send_message(message.chat.id, "Hi! Send me a Spotify artist URL (not playlists, albums, or tracks).")
    bot.register_next_step_handler(message, process_url)
    print("User pushed start.")

def is_valid_artist_url(url):
    """Checks if the URL is a valid Spotify artist URL."""
    match = re.match(r"https://open\.spotify\.com/artist/([a-zA-Z0-9]+)", url)
    return bool(match)

def get_artist_name(url):
    """Fetches the Spotify artist page and extracts the cleaned artist's name."""
    headers = {"User-Agent": "Mozilla/5.0"}
    try:
        response = requests.get(url, headers=headers, timeout=10)
        response.raise_for_status()
        soup = BeautifulSoup(response.text, 'html.parser')
        title_tag = soup.find("title")

        if title_tag:
            artist_name = title_tag.text.replace(" | Spotify", "").strip()
            
            # Remove unwanted suffixes
            artist_name = re.sub(
                r"\s*(Songs and Music|Songs|Songs, Albums, Bio & More)\s*$", 
                "", 
                artist_name, 
                flags=re.IGNORECASE
            )
            
            return artist_name.strip()
        else:
            return "Unknown Artist"
    except requests.RequestException as e:
        print(f"Error fetching artist name: {e}")
        return "Unknown Artist"

def process_url(message):
    url = message.text.strip()

    # Validate URL
    if not is_valid_artist_url(url):
        bot.send_message(message.chat.id, "Please send a valid Spotify artist URL, not a playlist, album, or track.")
        print(f"Rejected URL: {url}")  # Debugging
        return

    artist = get_artist_name(url)

    bot.send_message(message.chat.id, f"Downloading music for {artist}. This may take a while.")

    artist_directory = os.path.join(dldir, artist)
    os.makedirs(artist_directory, exist_ok=True)
    os.chdir(artist_directory)

    subprocess.run([
        f"{workingdir}bin/spotdl",
        "--format", "opus",
        "--bitrate", "80k",
        url
    ])

    bot.send_message(message.chat.id, f"Finished downloading {artist}.")
    print(f"Download completed for {artist}.")
    bot.send_message(message.chat.id, "Send another artist URL or use /start to begin again.")

@bot.message_handler(func=lambda message: message.text.startswith("https://open.spotify.com/artist/"))
def process_direct_url(message):
    process_url(message)

@bot.message_handler(func=lambda message: True)
def echo_all(message):
    bot.reply_to(message, "I don't understand. Please send a Spotify artist URL.")

if __name__ == "__main__":
    bot.polling()