import time
import network
import urequests
from machine import Pin
from wind_direction import WindVane
from air_quality import COSensor
from DHT22 import Environment 

# --- CONFIGURATION ---
WIFI_SSID = "YOUR_WIFI_USERNAME"
WIFI_PASS = "YOUR_WIFI_PASSWORD"
THINGSPEAK_WRITE_KEY = "YOUR_THINGSPEAK_WRITE_KEY"

DIR_MAP = {
    "North": 0, "North-East": 45, "East": 90, "South-East": 135,
    "South": 180, "South-West": 225, "West": 270, "North-West": 315, "Calm": 0
}

# --- INITIALIZE HARDWARE ---
vane = WindVane(12, 13, 14, 15)
co_meter = COSensor(26)
weather = Environment(16)
led = Pin("LED", Pin.OUT)

def connect_wifi():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(WIFI_SSID, WIFI_PASS)
    print("Connecting to WiFi...", end="")
    timeout = 15
    while timeout > 0:
        if wlan.isconnected():
            print("\nConnected! IP:", wlan.ifconfig()[0])
            return True
        timeout -= 1
        time.sleep(1)
    return False

if connect_wifi():
    print("Calibrating CO Sensor...")
    co_meter.calibrate()
    # Safety: If RO is 0, the sensor is likely not getting 5V power
    if hasattr(co_meter, 'RO') and co_meter.RO == 0:
        print("CRITICAL: CO Sensor RO is 0. Check 5V (VBUS) wiring!")

    while True:
        try:
            led.on()
            
            # 1. Read Sensors
            dir_text = vane.get_direction()
            dir_degree = DIR_MAP.get(dir_text, 0)
            
            # Safety check to avoid "Divide by Zero" error
            co_ppm = 0.0
            if hasattr(co_meter, 'RO') and co_meter.RO > 0:
                co_ppm = co_meter.read_ppm()
            
            env = weather.get_data()
            temp = env['temp'] if env["status"] == "OK" else 0
            hum = env['hum'] if env["status"] == "OK" else 0

            # 2. Build URL (ORDER: 1:Wind, 2:Temp, 3:Hum, 4:CO)
            url = f"https://api.thingspeak.com/update?api_key={THINGSPEAK_WRITE_KEY}"
            url += f"&field1={dir_degree}&field2={temp}&field3={hum}&field4={co_ppm}"

            # 3. Send Data
            print(f"Sending: Wind:{dir_text}, Temp:{temp}, Hum:{hum}, CO:{co_ppm:.2f}")
            response = urequests.get(url)
            print(f"ThingSpeak Response: {response.status_code}")
            response.close()
            
            led.off()
            time.sleep(1800) # ThingSpeak Free Tier limit
            
        except Exception as e:
            print(f"Error: {e}")
            time.sleep(5)
