import json
import re

from src.Library import *

import re

PROTECTED_ARTISTS = {
    "Tyler, The Creator",
    "The Good, The Bad & The Queen",
}

class LocalParser:
    def __init__(self):
        self.track_map: dict[str, Track] = {}
        self.artist_map: dict[str, Artist] = {}
        self.album_map: dict[str, Album] = {}
        self.library = Library()


    def parse_artists(self, data: str) -> List[Artist]:
        if not data:
            raise "No artist found"

        artists = []

        for artist_data in data:
            name = artist_data
            artist_id = name

            if artist_id in self.artist_map:
                artists.append(self.artist_map[artist_id])
                continue

            artist = Artist()
            artist.id = artist_id
            artist.title = name

            self.artist_map[artist_id] = artist
            self.library.artists.append(artist)

            artists.append(artist)

        return artists

    def parse_album(self, data: str) -> Album:
        if not data:
            raise "album is none"

        name = data
        album_id = name

        if album_id in self.album_map:
            return self.album_map[album_id]

        album = Album()
        album.id = album_id
        album.title = name

        self.album_map[album_id] = album
        self.library.albums.append(album)

        return album


    def parse(self, tracks_file: Path) -> Library:
        tracks_content = json.loads(tracks_file.read_text())

        for track_id, data in tracks_content.items():
            track = Track()

            track.id = track_id
            track.title = data.get("name")
            track.artists = self.parse_artists(data.get("artists"))
            track.album = self.parse_album(data.get("album"))
            track.local_path = data.get("path")
            track.duration_ms = data.get("duration")
            track.has_lyrics = data.get("has_lyrics")

            if not track.album or not len(track.artists) or not track.title:
                raise "error parsing"

            self.track_map[track.id] = track
            self.library.tracks.append(track)

        for track_id, track in self.track_map.items():
            for artist in track.artists:
                if artist not in track.album.artists:
                    track.album.artists.append(artist)

        self.library.update_cache()

        self.library.name = "Local"

        return self.library


    def parse_track_item(self, id, track: dict[str, Any]) -> Track:

        return track
