using AngleSharp;
using AngleSharp.Dom;
using YouTubeMusicAPI.Client;

public class YoutubeMusicValidator : UriBasedSongValidatorBase
{
    public override string UriValidatorRegex => @"^(https?://)?(music\.youtube\.com/playlist\?list=)([a-zA-Z0-9_-]+)";

    private YouTubeMusicClient youtubeClient;

    public YoutubeMusicValidator(ILogger logger, SpotifyApiClient spotifyApiClient) : base(logger, spotifyApiClient)
    {
        youtubeClient = new YouTubeMusicClient(logger, "AT", null, null, null);
    }

    public override SongProvider GetSongProvider()
    {
        return SongProvider.YoutubeMusic;
    }

    public override async Task<bool> CanExtractSongMetadataAsync(Uri songUri)
    {
        return await this.CanValidateUriAsync(songUri);
    }

    public override async Task<Song> ValidateAsync(Uri songUri)
    {
        var match = this.GetUriMatch(songUri);
        var playlistId = match.Groups[3].Value;

        var playlistResult = await youtubeClient.GetCommunityPlaylistInfoAsync(playlistId);
        var songData = playlistResult.Songs[0];

        var title = songData.Name;
        var artist = songData.Artists[0].Name;

        var song = new Song
        {
            Name = title,
            Artist = artist,
            Url = songUri.ToString(),
            Provider = SongProvider.YoutubeMusic,
            SpotifyId = await this.LookupSpotifyIdAsync(title, artist)
        };

        return song;
    }
}