import time
import json
import wifi
import os

class PresencePlugController:

    def __init__(self, sensor, requests, devices, api_key,
                 debounce_sec=0.12, timeout_sec=120, min_api_interval=5):
        self.sensor = sensor
        self.requests = requests
        self.devices = devices
        self.api_key = api_key
        self.debounce_sec = debounce_sec
        self.timeout_sec = timeout_sec
        self.min_api_interval = min_api_interval

        self.device_id = None
        self.model_id = None
        self.current_key = None

        self.last_change_candidate = 0
        self.last_motion_time = 0
        self.last_api_time = 0
        self.motion_state = False
        self.last_raw = self.sensor.presence

        self.display_label = None
        self.status_label = None
        self.countdown_label = None
        self.led = None

        self.candidate_state = None
        self.committed_state = None
        self.last_candidate_change = 0.0
        self.consecutive_false_count = 0
        self.required_consecutive_false = 10

        self.device_states = {key: None for key in self.devices}

    # --- UI hooks ---
    def set_status_label(self, lbl):
        self.status_label = lbl

    def set_countdown_label(self, lbl):
        self.countdown_label = lbl

    def set_display_label(self, label_obj):
        self.display_label = label_obj

    def set_led(self, led_obj):
        self.led = led_obj


    def set_both_outlets(self, turn_on=True):
        print(f"[DEBUG] set_both_outlets called with turn_on={turn_on}")
        """
        Send a Govee API command to turn both outlets ON or OFF at the same time.
        """
        headers = {
            "Content-Type": "application/json",
            "Govee-API-Key": self.api_key
        }
        # Hardcoded device/model for both outlets (update if needed)
        device_id = "2A:FE:60:74:F4:54:97:7A"
        model_id = "H5082"
        value = "on" if turn_on else "off"
        body = {
            "device": device_id,
            "model": model_id,
            "cmd": {
                "name": "turn",
                "value": value
            }
        }
        # Update display label immediately
        if self.display_label:
            self.display_label.text = f"Both Plugs {'On' if turn_on else 'Off'}"
        print(f"Sending BOTH OUTLETS {value.upper()} command: {body}")
        try:
            response = self.requests.put(
                "https://developer-api.govee.com/v1/devices/control",
                headers=headers,
                data=json.dumps(body),
                timeout=5
            )
            print("Status:", response.status_code)
            print("Response:", response.text)
            if self.status_label:
                self.status_label.text = f"Both {value.upper()}"
                self.status_label.color = 0x00FF00 if turn_on else 0xFF0000
        except Exception as e:
            print("Govee BOTH OUTLETS command failed:", e)
              

    # --- Device selection ---
    def set_active_device(self, key):
        if key in self.devices:
            self.device_id = self.devices[key]["device"]
            self.model_id = self.devices[key]["model"]
            self.current_key = key
            print(f"Switched to Plug {key}: {self.device_id}")

            self.update_display("Off")

            if self.status_label:
                if key == "C":
                    self.status_label.text = "Both OFF"
                else:
                    self.status_label.text = f"{key} OFF"
                self.status_label.color = 0xFF0000

            self.motion_state = False
            self.device_states[key] = None
        else:
            print(f"Device key {key} not found")

    def update_display(self, state):
        if self.display_label and self.current_key:
            if self.current_key == "C":
                self.display_label.text = f"Both Plugs {state}"
            else:
                self.display_label.text = f"Plug {self.current_key} {state}"

    # --- Govee payload ---
    def build_payload(self, value):
        return {
            "device": self.device_id,
            "model": self.model_id,
            "cmd": {
                "name": "toggle",
                "value": value
            }
        }

    # --- Govee API with Wi-Fi keepalive ---
    def send_govee_put(self, value):
        desired_state = "on" if value == "1_1" else "off"

        if self.status_label:
            outlet = self.current_key if self.current_key else "?"
            # Show 'Both ON/OFF' for C, 'A ON/OFF' or 'B ON/OFF' for A/B
            if outlet == "C":
                if value == "1_1":
                    self.status_label.text = "Both ON"
                    self.status_label.color = 0x00FF00
                else:
                    self.status_label.text = "Both OFF"
                    self.status_label.color = 0xFF0000
            elif outlet in ("A", "B"):
                if value == "1_1":
                    self.status_label.text = f"{outlet} ON"
                    self.status_label.color = 0x00FF00
                else:
                    self.status_label.text = f"{outlet} OFF"
                    self.status_label.color = 0xFF0000
            else:
                if value == "0_1":
                    self.status_label.text = f"Outlet {outlet} ON"
                    self.status_label.color = 0x00FF00
                else:
                    self.status_label.text = f"Outlet {outlet} OFF"
                    self.status_label.color = 0xFF0000

        current_state = self.device_states.get(self.current_key)
        if current_state == desired_state:
            print(f"Skipping redundant '{desired_state}' command for device {self.current_key}")
            return

        now = time.monotonic()
        if now - self.last_api_time < self.min_api_interval:
            print("Skipping API call: too soon")
            return
        self.last_api_time = now

        # Wi-Fi keepalive before API call
        try:
            print("Pinging Wi-Fi before PUT...")
            self.requests.get(
                "http://connectivitycheck.gstatic.com/generate_204",
                timeout=3
            )
        except Exception as e:
            print("Ping failed, reconnecting:", e)
            try:
                wifi.radio.connect(os.getenv("CIRCUITPY_WIFI_SSID"),
                                   os.getenv("CIRCUITPY_WIFI_PASSWORD"))
                print("Reconnected Wi-Fi")
            except Exception as e2:
                print("Reconnect failed:", e2)
                return

        headers = {
            "Content-Type": "application/json",
            "Govee-API-Key": self.api_key
        }
        body = self.build_payload(value)
        print("Sending PUT:", body)

        try:
            response = self.requests.put(
                "https://developer-api.govee.com/v1/devices/control",
                headers=headers,
                data=json.dumps(body),
                timeout=5
            )
            print("Status:", response.status_code)
            print("Response:", response.text)

            self.device_states[self.current_key] = desired_state

            if self.led:
                self.led.value = (value == "1_1")

            self.update_display("On" if value == "1_1" else "Off")

        except Exception as e:
            print("Govee PUT failed:", e)

    # --- Presence logic ---
    def update(self):
        if not self.sensor.data_ready or not self.device_id:
            return

        now = time.monotonic()
        raw = bool(self.sensor.presence or self.sensor.motion)

        print(raw)

        if self.candidate_state is None:
            self.candidate_state = raw
            self.last_candidate_change = now
            self.consecutive_false_count = 0 if raw else 1

        if raw:
            self.consecutive_false_count = 0
        else:
            self.consecutive_false_count += 1

        if raw:
            candidate = True
        else:
            if self.consecutive_false_count >= self.required_consecutive_false:
                candidate = False
            else:
                candidate = self.candidate_state

        if candidate != self.candidate_state:
            self.candidate_state = candidate
            self.last_candidate_change = now
            return

        if (now - self.last_candidate_change) < self.debounce_sec:
            return

        if candidate != self.committed_state:
            self.committed_state = candidate
            print("Committed presence:", self.committed_state)
            if self.committed_state:
                self.last_motion_time = now
                if not self.motion_state:
                    self.motion_state = True
                # Turn ON selected outlet or both if 'C'
                if self.current_key == "C":
                    self.set_both_outlets(turn_on=True)
                else:
                    self.send_govee_put("1_1")
            else:
                self.last_motion_time = now
                # Do NOT turn off yet; wait for timeout before sending OFF command and updating label
            return

        if self.committed_state:
            self.motion_state = True
            if self.countdown_label:
                self.countdown_label.text = ""
            self.last_motion_time = now
            return

        if not self.committed_state and self.motion_state:
            remaining = int(self.timeout_sec - (now - self.last_motion_time))
            if remaining < 0:
                remaining = 0
            if self.countdown_label:
                self.countdown_label.text = f"{remaining}s"
            # Do NOT update status label to OFF here; only after timeout
        else:
            if self.countdown_label:
                self.countdown_label.text = ""

        if self.motion_state and (now - self.last_motion_time >= self.timeout_sec):
            if self.current_key == "C":
                print("Occupancy timeout reached -> sending BOTH OFF")
                self.set_both_outlets(turn_on=False)
            else:
                print(f"Occupancy timeout reached -> sending {self.current_key} OFF")
                self.send_govee_put("1_0")
            self.motion_state = False
            return