using System.Text.RegularExpressions;
using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Html.Dom;

public class SpotifyValidator : UriBasedSongValidatorBase
{
    public override string UriValidatorRegex => @"^(https?://)?open.spotify.com/track/([a-zA-Z0-9_-]{22})(\?si=[a-zA-Z0-9_-]+)?$";

    public SpotifyValidator(ILogger _logger, SpotifyApiClient spotifyApiClient) : base(_logger, spotifyApiClient)
    { }

    public override Task<bool> CanExtractSongMetadataAsync(Uri songUri)
    {
        return Task.FromResult(this.CanValidateUri(songUri));
    }

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

    public override async Task<Song> ValidateAsync(Uri songUri)
    {
        var regexp = new Regex(UriValidatorRegex, RegexOptions.IgnoreCase);
        var trackIdMatch = regexp.Match(songUri.ToString()).Groups[2].Value;

        var track = await _spotifyApiClient.GetTrackByIdAsync(trackIdMatch);

        var song = new Song
        {
            Name = track.Name,
            Artist = track.Artists.FirstOrDefault()?.Name ?? "Unknown Artist",
            Url = songUri.ToString(),
            Provider = SongProvider.Spotify,
            SpotifyId = trackIdMatch
        };

        return song;
    }
}