import enum
import json
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse, FileResponse
from fastapi.middleware.cors import CORSMiddleware
import os

from urllib3 import request
from yandex_music import Client
from mutagen.mp3 import MP3
from mutagen.id3 import TIT2, TALB, TPE1, APIC, USLT



def save_track_with_metadata(trackId, download = True):
    track = client.tracks([trackId])[0]
    # Параметры для метаданных
    artist_name = track.artists[0].name if track.artists else "Неизвестный исполнитель"
    track_title = track.title if track.title else "Без названия"

    if(not download):
        return f"{artist_name} - {track_title}.mp3"
    album_name = track.albums[0].title if track.albums else track_title

    # Указываем имя файла для сохранения
    filename = f"{config['savePath']}/{artist_name} - {track_title}.mp3"
    cover_filename = f"{config['savePath']}/cover{trackId}.jpg"

    # Скачиваем трек
    track.download(filename)
    track.download_cover(cover_filename)

    audio = MP3(filename)
    audio.add_tags()

    if track.lyrics_info.has_available_sync_lyrics:
        audio.tags.add(USLT(encoding=3, lang="rus", desc="", text=client.tracks_lyrics(track_id=track.id, format_="LRC").fetchLyrics()))
    elif track.lyrics_info.has_available_text_lyrics:
        audio.tags.add(USLT(encoding=3, lang="rus", desc="", text=client.tracks_lyrics(track_id=track.id, format_="TEXT").fetchLyrics()))

    audio.tags.add(TIT2(encoding=3, text=track_title))  # Название
    audio.tags.add(TALB(encoding=3, text=album_name))  # Альбом
    audio.tags.add(TPE1(encoding=3, text=artist_name))  # Исполнитель
    with open(cover_filename, 'rb') as cover_file:
        cover_data = cover_file.read()
        audio.tags.add(APIC(encoding=3,
                            mime='image/jpeg',
                            type=3,
                            desc='Cover',
                            data=cover_data))
    audio.save()
    os.remove(cover_filename)
    return f"{artist_name} - {track_title}.mp3"


with open('configs/config.json', 'r', encoding='utf-8') as config_file:
    config = json.load(config_file)

client = Client(config['token']).init()
filterExplicit = True
played = []
bannedArtists = []
playedIds = []
partyActive = False

Tasks = []

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
def test():
    return "Hello, world!"

@app.get("/ab2h")
def test():
    return "Fuck You!"


@app.post("/search")
async def search(request: Request):
    search_data = await request.json()
    tracks = client.search(search_data.get("text")).tracks.results
    short_tracks = []

    for found in tracks:
        warming = "None"
        if filterExplicit and found.content_warning == "explicit":
            warming = "age"
        elif found.artists[0].name in bannedArtists:
            warming = "bannedArtists"
        elif found.trackId in played:
            warming = "Ordered"

        track_data = {
            "id": found['id'],
            "title": found['title'],
            "artist": found['artists'][0]['name'],
            "album": found['albums'][0]['title'],
            "image": f"https://{found['og_image'].replace('%%', '200x200')}" if found['og_image'] else None,
            "contentHint": warming
        }
        short_tracks.append(track_data)

    return JSONResponse(content=short_tracks)


@app.get("/get/{id}")
def get_song(id: int, request: Request):
    download_again = 'Range' not in request.headers
    file = save_track_with_metadata(id, download_again)
    return FileResponse(
        path=f"{config['savePath']}/{file}",
        media_type='audio/mpeg',
        filename=file
    )

@app.get("/active")
def active():
    global partyActive  # Указываем, что работаем с глобальной переменной
    partyActive = not partyActive  # Инвертируем значение
    return JSONResponse(content={"status": "ok"})

@app.get("/info")
def info():
    return JSONResponse(content={"status": "ok", "partyActive": partyActive})

@app.get("/order/{id}")
def order_song(id: int, request: Request):
    orderedTrack = client.tracks[id][0]
    warming = "None"
    if filterExplicit and orderedTrack.content_warning == "explicit":
        warming = "age"
    elif orderedTrack.artists[0].name in bannedArtists:
        warming = "bannedArtists"
    elif orderedTrack.trackId in played:
        warming = "Ordered"

    Tasks.append(Task(type=TaskType.ORDER_REQUEST, content=""))

    return JSONResponse(content={"contentHint": warming})

def delete_files_in_directory(directory):
    if os.path.exists(directory):
        for filename in os.listdir(directory):
            file_path = os.path.join(directory, filename)
            if os.path.isfile(file_path):
                os.remove(file_path)


if __name__ == "__main__":
    delete_files_in_directory(f"{config['savePath']}")
    import uvicorn

    uvicorn.run(app, host="0.0.0.0", port=5000, ssl_keyfile='configs/cert.key', ssl_certfile='configs/cert.crt')

добавь сюда вебсокет