from dataclasses import dataclass
from sqlite3 import Cursor

from connect import get_connection


def init_db(db: Cursor):
    db.execute("""
        CREATE TABLE IF NOT EXISTS songs (
            uuid TEXT PRIMARY KEY,
            title TEXT NOT NULL,
            artist TEXT NOT NULL,
            tags TEXT NOT NULL,
            lastfm_image_id TEXT NOT NULL,
            youtube_id TEXT NOT NULL
        );
    """)


@dataclass(frozen=True, slots=True, kw_only=True)
class Song:
    uuid: str
    title: str
    artist: str
    tags: list[str]
    image_id: str
    youtube_id: str


def get_song_by_uuid(uuid: str) -> Song | None:
    conn = get_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM songs WHERE uuid = ?", (uuid,))
    row = cursor.fetchone()
    conn.close()

    if row is None:
        return None

    song = Song(uuid=row["uuid"], title=row["title"], artist=row["artist"], tags=list(filter(None, row["tags"].split(","))), image_id=row["lastfm_image_id"], youtube_id=row["youtube_id"])
    return song


def get_song_by_title_artist(title: str, artist: str) -> Song | None:
    conn = get_connection()
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM songs WHERE title = ? AND artist = ?", (title, artist))
    row = cursor.fetchone()
    conn.close()

    if row is None:
        return None

    song = Song(uuid=row["uuid"], title=row["title"], artist=row["artist"], tags=list(filter(None, row["tags"].split(","))), image_id=row["lastfm_image_id"], youtube_id=row["youtube_id"])
    return song


def add_song_in_db(song: Song) -> None:
    conn = get_connection()
    cursor = conn.cursor()

    cursor.execute(
        """
        INSERT OR REPLACE INTO songs (uuid, title, artist, tags, lastfm_image_id, youtube_id)
        VALUES (?, ?, ?, ?, ?, ?)
        """,
        (song.uuid, song.title, song.artist, ",".join(song.tags), song.image_id, song.youtube_id),
    )  # Updates song info if it already exists

    conn.commit()
    conn.close()
