using System.Text;

namespace Aberwyn.Data
{
    public class HdTorrentsTrackerScraper
    {
        private readonly HttpClient _httpClient;
        private readonly ILogger<HdTorrentsTrackerScraper> _logger;

        public HdTorrentsTrackerScraper(HttpClient httpClient, ILogger<HdTorrentsTrackerScraper> logger)
        {
            _httpClient = httpClient;
            _logger = logger;
        }

        public async Task<(int seeders, int leechers, int completed)> ScrapeHdTorrents(string infoHash, string downloadKey)
        {
            try
            {
                if (string.IsNullOrEmpty(infoHash) || string.IsNullOrEmpty(downloadKey))
                    return (0, 0, 0);

                // Konvertera hex InfoHash till URL-encoded bytes
                var infoHashBytes = HexStringToBytes(infoHash);

                //%67%2e%d6%f9%30%e9%33%88%e3%1b%c6%f0%85%f5%f7%78%44%05%10%e7
                var encodedInfoHash = Uri.EscapeDataString(Encoding.GetEncoding("ISO-8859-1").GetString(infoHashBytes));
                var encodedInfoHashv2 = EncodeInfoHash(infoHash);

                // Bygga scrape URL baserat på HD-Torrents format
                var scrapeUrl = $"https://hdts-announce.ru/scrape.php?pid=98d498dedff78ba0334f662d151eb19b7?info_hash={encodedInfoHashv2}";

                _logger.LogInformation("Scraping HD-Torrents: {Url}", scrapeUrl);

                var response = await _httpClient.GetAsync(scrapeUrl);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsByteArrayAsync(); // Fix: Content.ReadAsByteArrayAsync()
                    return ParseBencodeResponse(content);
                }
                else
                {
                    _logger.LogWarning("Scrape failed with status: {StatusCode}", response.StatusCode);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to scrape HD-Torrents for InfoHash: {InfoHash}", infoHash);
            }

            return (0, 0, 0);
        }
        private static string EncodeInfoHash(string hex)
        {
            var bytes = HexStringToBytes(hex);
            return string.Concat(bytes.Select(b => $"%{b:X2}")).ToLower();
        }
        private static byte[] HexStringToBytes(string hex)
        {
            if (hex.Length % 2 != 0)
                throw new ArgumentException("Invalid hex string length.");

            var bytes = new byte[hex.Length / 2];
            for (int i = 0; i < bytes.Length; i++)
            {
                bytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16);
            }
            return bytes;
        }

        private (int seeders, int leechers, int completed) ParseBencodeResponse(byte[] data)
        {
            try
            {
                // Enkel bencode parsing för tracker response
                var response = System.Text.Encoding.UTF8.GetString(data);

                // Tracker response är vanligtvis i format:
                // d5:filesd20:[info_hash]d8:completei[antal]e9:downloadedi[antal]e10:incompletei[antal]eee

                // Hitta complete (seeders)
                var completeMatch = System.Text.RegularExpressions.Regex.Match(response, @"8:completei(\d+)e");
                var seeders = completeMatch.Success ? int.Parse(completeMatch.Groups[1].Value) : 0;

                // Hitta incomplete (leechers)  
                var incompleteMatch = System.Text.RegularExpressions.Regex.Match(response, @"10:incompletei(\d+)e");
                var leechers = incompleteMatch.Success ? int.Parse(incompleteMatch.Groups[1].Value) : 0;

                // Hitta downloaded (completed)
                var downloadedMatch = System.Text.RegularExpressions.Regex.Match(response, @"9:downloadedi(\d+)e");
                var completed = downloadedMatch.Success ? int.Parse(downloadedMatch.Groups[1].Value) : 0;

                return (seeders, leechers, completed);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Failed to parse bencode response");
                return (0, 0, 0);
            }
        }
    }
}
