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

public class YoutubeValidator : UriBasedSongValidatorBase
{
    private YouTubeMusicClient youtubeClient;

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

    public override string UriValidatorRegex => @"^(https?://)?(www\.)?(youtube\.com/watch\?v=|youtu\.be/)([a-zA-Z0-9_-]{11})";

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

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

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

        var songData = await youtubeClient.GetSongVideoInfoAsync(songId);

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

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

        return song;
    }
}