import machine
import utime
import dht
import network
import urequests

# --- SAFETY DELAY (Essential for Deep Sleep) ---
print("Wait 5s... (Press Stop to edit)")
utime.sleep(5)

# --- SETTINGS ---
WIFI_SSID = "WIFI_ID"
WIFI_PASS = "WIFI_PASS"
THINGSPEAK_API_KEY = "YOUR_API_KEY"
THINGSPEAK_URL = "YOUR THINKSPEAK URL"

# --- PRODUCTION DURATIONS (in seconds now) ---
AVG_SECONDS = 1800      # 30 minutes measuring (WiFi OFF)
SLEEP_SECONDS = 1800   # 30 minutes sleeping (Power OFF)
SAMPLE_INTERVAL = 900    # 5 Seconds between sensor reads

# --- PINS ---
ir_n = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP)
ir_e = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)
ir_s = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP)
ir_w = machine.Pin(15, machine.Pin.IN, machine.Pin.PULL_UP)
dht_sensor = dht.DHT11(machine.Pin(16))
led = machine.Pin("LED", machine.Pin.OUT)

def get_wind_direction():
    # RAW readings: 0 = plate blocking sensor, 1 = free (wind direction side)
    n_raw = ir_n.value()
    e_raw = ir_e.value()
    s_raw = ir_s.value()
    w_raw = ir_w.value()

    # True means "this side is free" (candidate wind direction)
    n = (n_raw == 1)
    e = (e_raw == 1)
    s = (s_raw == 1)
    w = (w_raw == 1)

    # Optional: uncomment for debugging
    # print("RAW  -> N:", n_raw, "E:", e_raw, "S:", s_raw, "W:", w_raw)
    # print("LOGIC-> N:", n, "E:", e, "S:", s, "W:", w)

    # Map to 0–7 (adjust if your truth table is different)
    # 0=N,1=NE,2=E,3=SE,4=S,5=SW,6=W,7=NW, -1=Unknown/No wind

    # 2-sensor diagonals first (if your vane gives two free sides)
    if n and e and not s and not w:
        return 1  # NE
    if e and s and not n and not w:
        return 3  # SE
    if s and w and not n and not e:
        return 5  # SW
    if w and n and not e and not s:
        return 7  # NW

    # Single-sensor cardinals
    if n and not e and not s and not w:
        return 0  # N
    if e and not n and not s and not w:
        return 2  # E
    if s and not n and not e and not w:
        return 4  # S
    if w and not n and not e and not s:
        return 6  # W

    # If all blocked or some weird combo
    return -1

def run_cycle():
    # 1. Turn OFF WiFi initially to save power/reduce noise
    wlan = network.WLAN(network.STA_IF)
    wlan.active(False)
    led.off()

    # 2. Sampling Loop
    print(f"PRODUCTION MODE: Sampling for {AVG_SECONDS} seconds...")
    
    total_temp = 0
    total_hum = 0
    count = 0
    max_samples = int(AVG_SECONDS / SAMPLE_INTERVAL)

    for i in range(max_samples):
        try:
            dht_sensor.measure()
            t = dht_sensor.temperature()
            h = dht_sensor.humidity()
            
            if i % 60 == 0:
                print(f"Sample {i+1}/{max_samples}...")

            if -10 < t < 80 and 0 < h <= 100:
                total_temp += t
                total_hum += h
                count += 1
        except Exception:
            pass
        
        utime.sleep(SAMPLE_INTERVAL)

    avg_t = round(total_temp / count, 1) if count > 0 else 0
    avg_h = round(total_hum / count, 1) if count > 0 else 0
    wind = get_wind_direction()

    print(f"--- FINISHED SAMPLING. AVG: T={avg_t}, H={avg_h}, WindID={wind} ---")

    # 3. Robust WiFi connection
    connected = False
    MAX_RETRIES = 5 
    
    for retry in range(MAX_RETRIES):
        print(f"📡 Connection Attempt {retry+1}/{MAX_RETRIES}...")
        
        wlan.active(True)
        wlan.connect(WIFI_SSID, WIFI_PASS)
        
        attempts = 0
        while not wlan.isconnected() and attempts < 10:
            utime.sleep(1)
            attempts += 1
            
        if wlan.isconnected():
            print("WiFi Connected!")
            connected = True
            break
        else:
            print("Connection failed. Resetting radio...")
            wlan.active(False)
            utime.sleep(2)

    # 4. Upload Data
    if connected:
        led.on()
        print("Uploading...")
        try:
            url = (
                f"{THINGSPEAK_URL}?api_key={THINGSPEAK_API_KEY}"
                f"&field1={wind}&field2={avg_t}&field3={avg_h}"
            )
            urequests.get(url).close()
            print("Uploaded to ThingSpeak")
        except Exception as e:
            print("Upload Failed", e)
    else:
        print("ALL WiFi Attempts Failed. Skipping upload.")

    # 5. Deep Sleep
    print(f"Sleeping for {SLEEP_SECONDS} seconds...")
    utime.sleep(1)
    machine.deepsleep(SLEEP_SECONDS * 1000)

# --- EXECUTE ---
try:
    run_cycle()
except Exception as e:
    print("Fatal Error:", e)
    machine.reset()