using System.Net;
using System.Text.RegularExpressions;
using JobsMedical.Web.Models;

namespace JobsMedical.Web.Services.Scraping;

/// <summary>
/// Reads public Telegram channels via the web preview (https://t.me/s/&lt;channel&gt;) — no bot
/// token needed for public channels. Enabled + channel list come from the admin settings (DB).
/// </summary>
public class TelegramListingSource : IListingSource
{
    private readonly ScrapeHttpClients _clients;
    private readonly ILogger<TelegramListingSource> _log;

    public TelegramListingSource(ScrapeHttpClients clients, ILogger<TelegramListingSource> log)
    {
        _clients = clients;
        _log = log;
    }

    public string Name => "تلگرام";

    public async Task<IReadOnlyList<ScrapedItem>> FetchAsync(AppSetting s, CancellationToken ct = default)
    {
        var channels = AppSetting.SplitList(s.TelegramChannels);
        if (!s.TelegramEnabled || channels.Count == 0) return Array.Empty<ScrapedItem>();

        var client = _clients.For(s, s.TelegramUseProxy);
        var items = new List<ScrapedItem>();
        foreach (var ch in channels.Select(c => c.TrimStart('@')).Where(c => c.Length > 0))
        {
            try
            {
                var html = await client.GetStringAsync($"https://t.me/s/{ch}", ct);
                foreach (var text in ExtractMessages(html).Take(20))
                    items.Add(new ScrapedItem($"تلگرام/{ch}", text, $"https://t.me/{ch}"));
            }
            catch (Exception ex) { _log.LogWarning(ex, "Telegram fetch failed for {Channel}", ch); }
        }
        return items;
    }

    private static IEnumerable<string> ExtractMessages(string html)
    {
        foreach (Match m in Regex.Matches(html,
            "<div class=\"tgme_widget_message_text[^\"]*\"[^>]*>(.*?)</div>", RegexOptions.Singleline))
        {
            var text = HtmlUtil.ToPlainText(m.Groups[1].Value);
            if (text.Length >= 15) yield return text;
        }
    }
}

internal static class HtmlUtil
{
    public static string ToPlainText(string html)
    {
        var s = Regex.Replace(html, "<br\\s*/?>", "\n", RegexOptions.IgnoreCase);
        s = Regex.Replace(s, "<[^>]+>", "");
        s = WebUtility.HtmlDecode(s);
        s = Regex.Replace(s, "[ \\t]+", " ");
        return s.Trim();
    }
}
