import os
import time
import microcontroller
import adafruit_connection_manager
import wifi
import adafruit_requests

# Initalize Wifi, Socket Pool, Request Session
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)
SSL_CONTEXT = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
# adafruit_requests.Session keep outside the main loop
# otherwise you get Out of Socket errors.
requests = adafruit_requests.Session(pool, SSL_CONTEXT)

# Use settings.toml for credentials
ssid = os.getenv("CIRCUITPY_WIFI_SSID")
password = os.getenv("CIRCUITPY_WIFI_PASSWORD")

SOURCE = "https://httpbin.org/get"
HEADER = {"user-agent": "blinka/1.0.0"}

while True:
  # Connect to Wi-Fi
  print("\nConnecting to WiFi...")
  while not wifi.radio.connected:
    try:
      wifi.radio.connect(ssid, password)
    except ConnectionError as e:
      print(f"❌ Connection Error: {e}")
      time.sleep(60)
  print("📡 Wifi!")

  while wifi.radio.connected:
    try:
      
      try:
        with requests.get(url=SOURCE, headers=HEADER) as response:
          response_json = response.json()
      # Request error catcher. If script fails during request.
      except (OSError, KeyError) as e:
        if e.errno == -2:
          print(f"❌ gaierror (DNS failure), waiting to hard reset {e}")
          time.sleep(240)
          microcontroller.reset()
        print(f"❌ Key Error: {e}")
        time.sleep(60)
        
      # Your online API section goes here
      response_headers = response.headers
      print(f"Response Headers: {response_headers}")
      
    # General error catcher. If script fails after a successful request.
    except (OSError, ValueError, RuntimeError) as e:
      print(f"❌ General Exception Error: {e}")
      time.sleep(60)
      break  # breaks to while True to re-check WiFi status
    time.sleep(300)  # If everything succeeds, time until next poll update