import time
import board
import wifi
import os
import digitalio
import displayio
import terminalio
import microcontroller
import neopixel
import adafruit_ntp
import rtc
from adafruit_display_text import label
import adafruit_connection_manager
import adafruit_requests
import adafruit_sths34pf80
from presence_plug_controller import PresencePlugController

# --- Control Display Backlight ---
display_is_off = False

# --- Wi-Fi ---
SSID = os.getenv("CIRCUITPY_WIFI_SSID")
PASS = os.getenv("CIRCUITPY_WIFI_PASSWORD")
GOVEE_KEY = os.getenv("GOVEE_API_KEY")

# --- Timezone ---
val = os.getenv("TZ_OFFSET", "-7")
try:
    TZ_OFFSET = int(val.strip().replace('"', '').replace("'", ""))
except Exception:
    TZ_OFFSET = -7

# --- Govee Devices ---
GOVEE_DEVICES = {
    "A": {"device": os.getenv("DEVICE_1"), "model": os.getenv("MODEL_1")},
    "B": {"device": os.getenv("DEVICE_2"), "model": os.getenv("MODEL_2")},
    "C": {"device": os.getenv("DEVICE_3"), "model": os.getenv("MODEL_3")},
}

# --- Buttons ---
button_a = digitalio.DigitalInOut(board.BUTTON)
button_a.switch_to_input(pull=digitalio.Pull.UP)

button_b = digitalio.DigitalInOut(board.D1)
button_b.switch_to_input(pull=digitalio.Pull.DOWN)

button_c = digitalio.DigitalInOut(board.D2)
button_c.switch_to_input(pull=digitalio.Pull.DOWN)

# --- Button state tracking ---
last_button_a = False
last_button_b = False
last_button_c = False

def check_button_selection():
    global last_button_a, last_button_b, last_button_c

    current_a = not button_a.value
    current_b = button_b.value
    current_c = button_c.value

    selection = None

    if current_a and not last_button_a:
        selection = "A"
    elif current_b and not last_button_b:
        selection = "B"
    elif current_c and not last_button_c:
        selection = "C"

    last_button_a = current_a
    last_button_b = current_b
    last_button_c = current_c

    if selection:
        microcontroller.nvm[0] = ord(selection)
        return selection

    return None

# --- NeoPixel Heartbeat ---
pixel = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)
heartbeat = False
last_heartbeat = time.monotonic()

# --- LED ---
led = digitalio.DigitalInOut(board.LED)
led.switch_to_output(value=False)

# --- Display ---
display = board.DISPLAY

group = displayio.Group()
display.root_group = group

text_label = label.Label(terminalio.FONT, text="Initializing...", x=10, y=display.height - 30, scale=2)
group.append(text_label)

status_label = label.Label(
    terminalio.FONT,
    text="",
    scale=4,
    color=0xFFFFFF,
    anchor_point=(0.5, 0.5),
    anchored_position=(display.width // 2, display.height // 2)
)
group.append(status_label)

countdown_label = label.Label(
    terminalio.FONT,
    text="",
    scale=2,
    color=0xFFFF00,
    anchor_point=(1.0, 1.0),
    anchored_position=(display.width - 5, display.height - 5)
)
group.append(countdown_label)

# --- Date/Time Label ---
datetime_label = label.Label(
    terminalio.FONT,
    text="",
    scale=2,
    color=0x00FFFF,
    anchor_point=(0.5, 0.0),
    anchored_position=(display.width // 2, 5)
)
group.append(datetime_label)

# --- TFT Heartbeat Dot ---
heartbeat_bitmap = displayio.Bitmap(6, 6, 2)
heartbeat_palette = displayio.Palette(2)
heartbeat_palette[0] = 0x000000
heartbeat_palette[1] = 0x00FF00

for x in range(6):
    for y in range(6):
        heartbeat_bitmap[x, y] = 1

heartbeat_tile = displayio.TileGrid(
    heartbeat_bitmap,
    pixel_shader=heartbeat_palette,
    x=display.width - 10,
    y=10
)
group.append(heartbeat_tile)

tft_heartbeat = False
last_tft_heartbeat = time.monotonic()

# --- Internet health state ---
internet_ok = True
ping_flash_until = 0

# --- Connect Wi-Fi ---
print(f"Connecting to {SSID}...")
wifi.radio.connect(SSID, PASS)
print("Connected to Wi-Fi:", wifi.radio.ipv4_address)

# --- Create ONE socket pool ---
pool = adafruit_connection_manager.get_radio_socketpool(wifi.radio)

# --- NTP Time Sync ---
print("Syncing time with NTP...")
ntp = adafruit_ntp.NTP(pool, tz_offset=TZ_OFFSET)
rtc.RTC().datetime = ntp.datetime
print("Time synced:", time.localtime())

# --- HTTPS session ---
ssl_context = adafruit_connection_manager.get_radio_ssl_context(wifi.radio)
requests = adafruit_requests.Session(pool, ssl_context)
requests.timeout = 5

# --- Sensor ---
i2c = board.I2C()
sths = adafruit_sths34pf80.STHS34PF80(i2c)

# --- Controller ---
controller = PresencePlugController(
    sensor=sths,
    requests=requests,
    devices=GOVEE_DEVICES,
    api_key=GOVEE_KEY
)

controller.set_display_label(text_label)
controller.set_status_label(status_label)
controller.set_countdown_label(countdown_label)
controller.set_led(led)

# --- Prompt for button selection ---
selection = None
selection_locked = False
text_label.text = "Select an option\nButton A, B, or C"
text_label.y = display.height - 45
status_label.text = ""
start_time = time.monotonic()
while (time.monotonic() - start_time) < 5:
    selection = check_button_selection()
    if selection:
        print(f"Button pressed during prompt: {selection}")
        controller.set_active_device(selection)
        button_a.switch_to_input()
        button_b.switch_to_input()
        button_c.switch_to_input()
        selection_locked = True
        break
    time.sleep(0.05)

# --- Restore last plug selection ---
try:
    if not selection:
        stored = microcontroller.nvm[0]
        if stored in (ord("A"), ord("B"), ord("C")):
            default_key = chr(stored)
            print(f"Restoring last selected plug: {default_key}")
            controller.set_active_device(default_key)
        else:
            print(f"NVM[0] invalid: {stored} — defaulting to A")
            controller.set_active_device("A")
except IndexError:
    if not selection:
        print("NVM[0] not initialized — defaulting to A")
        controller.set_active_device("A")

# --- Keepalive timer ---
last_ping = time.monotonic()

# --- Clock update timer ---
last_clock_update = 0

# --- Main loop ---
print("Starting motion detection loop...")
print("Raw NVM[0] value:", microcontroller.nvm[0])

text_label.y = display.height - 15

while True:
    if not selection_locked:
        selection = check_button_selection()
        if selection:
            print("Button pressed:", selection)
            if selection == "A":
                controller.set_active_device("A")
            elif selection == "B":
                controller.set_active_device("B")
            elif selection == "C":
                print("[DEBUG] Calling set_both_outlets(turn_on=True) from code.py")
                if hasattr(controller, "set_both_outlets"):
                    controller.set_both_outlets(turn_on=True)
                else:
                    print("set_both_outlets() not implemented in controller!")
            button_a.switch_to_input()
            button_b.switch_to_input()
            button_c.switch_to_input()
            selection_locked = True
            time.sleep(0.5)

    # --- Wi-Fi keepalive every 30 seconds ---
    now = time.monotonic()
    if now - last_ping > 30:
        try:
            print("Pinging Wi-Fi...")
            ping_flash_until = time.monotonic() + 0.5
            requests.get("http://connectivitycheck.gstatic.com/generate_204", timeout=3)
            print("Ping OK")
            internet_ok = True
        except Exception as e:
            print("Ping failed:", e)
            internet_ok = False
        last_ping = now

    # --- TFT Heartbeat Logic ---
    now = time.monotonic()
    if not internet_ok:
        heartbeat_palette[1] = 0xFF0000
        last_tft_heartbeat = now
    else:
        if now < ping_flash_until:
            heartbeat_palette[1] = 0x0000FF
        else:
            if now - last_tft_heartbeat > 1:
                tft_heartbeat = not tft_heartbeat
                heartbeat_palette[1] = 0x00FF00 if tft_heartbeat else 0x000000
                last_tft_heartbeat = now

    # --- NeoPixel Heartbeat ---
    now = time.monotonic()
    if not internet_ok:
        pixel[0] = (50, 0, 0)
    elif now < ping_flash_until:
        pixel[0] = (0, 0, 50)
    else:
        if now - last_heartbeat > 1:
            heartbeat = not heartbeat
            pixel[0] = (0, 50, 0) if heartbeat else (0, 0, 0)
            last_heartbeat = now

    # --- Date/Time Display (update once per second) ---
    now = time.monotonic()
    if now - last_clock_update >= 1:
        now_struct = time.localtime()

        hour_12 = now_struct.tm_hour % 12
        if hour_12 == 0:
            hour_12 = 12
        am_pm = "a" if now_struct.tm_hour < 12 else "p"

        month_names = [
            "Jan", "Feb", "Mar", "Apr", "May", "Jun",
            "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
        ]

        day = now_struct.tm_mday
        if 11 <= day <= 13:
            suffix = "th"
        else:
            suffix = {1: "st", 2: "nd", 3: "rd"}.get(day % 10, "th")

        month_str = month_names[now_struct.tm_mon - 1]

        datetime_label.text = "{} {}{} {:2d}:{:02d}{}".format(
            month_str, day, suffix,
            hour_12, now_struct.tm_min, am_pm
        )

        last_clock_update = now

    # --- Auto display sleep/wake ---
    hour = now_struct.tm_hour
    if (hour >= 22 or hour < 6):
        if not display_is_off:
            print("Turning display OFF for night mode")
            display.brightness = 0.0
            display_is_off = True
    else:
        if display_is_off:
            print("Turning display ON for daytime")
            display.brightness = 1.0
            display_is_off = False

    controller.update()
    time.sleep(0.02)