using System;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

public class DiscogsService
{
    private readonly HttpClient _client = new HttpClient();
    private string Token; // Get from Discogs settings
    private string UserAgent;

    public DiscogsService(string token, string app, string version, string email)
    {
        Token = token;
        UserAgent = $"{app}/{version} (contact: {email})";
    }

    public async Task<List<string>> GetGenresAsync(string artist, string album)
    {
        // 1. Setup Headers (Crucial for Discogs)
        _client.DefaultRequestHeaders.Clear();
        _client.DefaultRequestHeaders.Add("User-Agent", UserAgent);
        _client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Discogs", $"token={Token}");

        // 2. Search for the release
        // We use the search endpoint to find the ID of the album first
        string searchUrl = $"https://api.discogs.com/database/search?artist={Uri.EscapeDataString(artist)}&release_title={Uri.EscapeDataString(album)}&type=release";

        try
        {
            var response = await _client.GetStringAsync(searchUrl);
            using var doc = JsonDocument.Parse(response);
            var firstResult = doc.RootElement.GetProperty("results").EnumerateArray().FirstOrDefault();

            if (firstResult.ValueKind == JsonValueKind.Undefined)
            {
                Console.WriteLine("No match found on Discogs.");
                 return new List<string>();
            }

            // 3. Extract Genre and Style from search result
            // Discogs provides these directly in the search results for releases!
            var genres = firstResult.GetProperty("genre").EnumerateArray().Select(g => g.GetString());
            var styles = firstResult.GetProperty("style").EnumerateArray().Select(s => s.GetString());

            Console.WriteLine($"--- Discogs Results for {album} ---");
            Console.WriteLine($"Genres: {string.Join(", ", genres)}");
            Console.WriteLine($"Styles: {string.Join(", ", styles)}");

            return genres.ToList();
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error: {ex.Message}"); 
        }
        return new List<string>();
    }
}