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

class TelegramClient
{
    private static readonly string BotToken = "7330819864:AAHx9GEL-G-WeH2ON5-ncdsbbhV6YaOqZzg";
    private static readonly string ApiUrl = $"https://api.telegram.org/bot{BotToken}/";

    static async Task Main()
    {
        Console.WriteLine("Telegram Bot Client Started...");

        while (true)
        {
            await ReceiveMessagesAsync();
            await Task.Delay(5000); // Polling delay
        }
    }

    private static async Task SendMessageAsync(string chatId, string message)
    {
        using HttpClient client = new HttpClient();
        var payload = new
        {
            chat_id = chatId,
            text = message
        };

        var content = new StringContent(JsonSerializer.Serialize(payload), Encoding.UTF8, "application/json");
        try
        {
            var response = await client.PostAsync(ApiUrl + "sendMessage", content);
            var responseText = await response.Content.ReadAsStringAsync();

            Console.WriteLine($"Response: {responseText}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error sending message: {ex.Message}");
        }
    }

    private static async Task ReceiveMessagesAsync()
    {
        using HttpClient client = new HttpClient();
        try
        {
            var response = await client.GetAsync(ApiUrl + "getUpdates");
            response.EnsureSuccessStatusCode();

            var responseText = await response.Content.ReadAsStringAsync();
            var updates = JsonSerializer.Deserialize<TelegramUpdateResponse>(responseText);

            if (updates?.Result != null)
            {
                foreach (var update in updates.Result)
                {
                    Console.WriteLine($"Received message from {update.Message.Chat.Id}: {update.Message.Text}");
                    await SendMessageAsync(update.Message.Chat.Id.ToString(), "Message received!");
                }
            }
        }
        catch (HttpRequestException httpEx)
        {
            Console.WriteLine($"HTTP error: {httpEx.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Unexpected error: {ex.Message}");
        }
    }
}

class TelegramUpdateResponse
{
    public TelegramUpdate[] Result { get; set; }
}

class TelegramUpdate
{
    public TelegramMessage Message { get; set; }
}

class TelegramMessage
{
    public TelegramChat Chat { get; set; }
    public string Text { get; set; }
}

class TelegramChat
{
    public long Id { get; set; }
}