using System.Text.Json;

while (true)
{
	using var http = new HttpClient();
	http.DefaultRequestHeaders.Add("Metadata", "true");
	try
	{
		var json = await http.GetStringAsync("http://169.254.169.254/metadata/scheduledevents?api-version=2020-07-01");
		var document = JsonSerializer.Deserialize<Document>(json);
		if (document != null)
		{
			Console.WriteLine(document.DocumentIncarnation);
			if (document.Events != null)
			{
				foreach (var item in document.Events)
				{
					if ("Preempt".Equals(item.EventType, StringComparison.OrdinalIgnoreCase) && "Scheduled".Equals(item.EventStatus, StringComparison.OrdinalIgnoreCase))
					{
						var dt = DateTime.Parse(item.NotBefore!);
						Console.WriteLine($"Will go down at {dt}.");
						return;
					}
				}
			}
		}
	}
	catch (Exception ex)
	{
		Console.WriteLine(ex);
	}
	finally
	{
		Thread.Sleep(5000);
	}
}

record Document
{
	public int? DocumentIncarnation { get; set; }
	public Event[]? Events { get; set; }
}
record Event
{
	public string? EventId { get; set; }
	public string? EventType { get; set; }
	public string? ResourceType { get; set; }
	public string[]? Resources { get; set; }
	public string? EventStatus { get; set; }
	public string? NotBefore { get; set; }
	public string? Description { get; set; }
	public string? EventSource { get; set; }
	public int? DurationInSeconds { get; set; }
}