import time
import requests
from pyfirmata import Arduino, util, INPUT


# ============================================================
# STUDENT SETTINGS
# ============================================================

COM_PORT = "COM4"
API_KEY = "smk_live_PASTE_YOUR_API_KEY_HERE"  # Replace with a new API key
DEVICE_NAME = "TEAM01-LAB8"

API_URL = "https://rasimmax.com/SmartManagement/api/v1/telemetry.php"
PING_URL = "https://rasimmax.com/SmartManagement/api/v1/ping.php"


# ============================================================
# ARDUINO PIN ASSIGNMENTS
# ============================================================

PIR_PIN = 2  # PIR OUT -> D2
LDR_PIN = 0  # LDR divider -> A0
LM35_PIN = 1  # LM35 Vout -> A1

# DHT11 DATA -> D3
# NOTE:
# Stock StandardFirmata cannot read DHT11 directly.


# ============================================================
# SETTINGS
# ============================================================

DARK_THRESHOLD = 350
UPLOAD_INTERVAL = 2.0

HTTP_TIMEOUT = 5
RECONNECT_DELAY = 5


# ============================================================
# API
# ============================================================


def api_headers():

    return {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json",
        "Accept": "application/json",
    }


def check_api():

    print("Checking SmartManagement API...")

    response = requests.get(PING_URL, headers=api_headers(), timeout=HTTP_TIMEOUT)

    if response.status_code != 200:
        raise RuntimeError(
            f"API authentication failed: HTTP {response.status_code}: {response.text}"
        )

    print("SmartManagement API: OK")


# ============================================================
# ARDUINO / FIRMATA
# ============================================================


def connect_arduino():

    print()
    print(f"Connecting to HC-06 on {COM_PORT}...")

    board = Arduino(COM_PORT)

    # Required for receiving sensor values
    iterator = util.Iterator(board)
    iterator.daemon = True
    iterator.start()

    # PIR
    pir = board.digital[PIR_PIN]
    pir.mode = INPUT
    pir.enable_reporting()

    # LDR
    ldr = board.analog[LDR_PIN]
    ldr.enable_reporting()

    # LM35 temperature sensor on analog A1
    lm35 = board.analog[LM35_PIN]
    lm35.enable_reporting()

    # Give Firmata time to start reporting
    time.sleep(2)

    print("Arduino / HC-06: CONNECTED")

    return board, pir, ldr, lm35


# ============================================================
# SENSOR READING
# ============================================================


def read_sensors(pir, ldr, lm35):

    motion_value = pir.read()
    light_value = ldr.read()
    lm35_value = lm35.read()

    # Firmata may return None briefly after connection
    if motion_value is None or light_value is None or lm35_value is None:
        return None

    motion = bool(motion_value)

    # pyFirmata analog input = 0.0 ... 1.0
    # convert to Arduino-style 0 ... 1023
    light = int(light_value * 1023)

    # pyFirmata returns a normalized voltage reading (0.0 to 1.0).
    # For Arduino Uno with 5.0 V analog reference and LM35 at 10 mV/C:
    # temperature_C = (reading * 5.0 V) / (0.010 V/C).
    temperature_c = round(lm35_value * 500.0, 2)

    return motion, light, temperature_c


# ============================================================
# SMART ROOM LOGIC
# ============================================================


def create_packet(motion, light, temperature_c):

    dark = light < DARK_THRESHOLD

    if motion and dark:
        status = "ALERT"
        message = "Motion detected while room is dark"

    elif motion:
        status = "MOTION"
        message = "Motion detected"

    elif dark:
        status = "DARK"
        message = "Room is dark"

    else:
        status = "NORMAL"
        message = "Room condition is normal"

    packet = {
        "device": DEVICE_NAME,
        "metrics": {"motion": motion, "light": light, "temperature": temperature_c},
        "status": status,
        "message": message,
    }

    return packet


# ============================================================
# UPLOAD TO SMARTMANAGEMENT
# ============================================================


def upload_data(packet):

    response = requests.post(
        API_URL, headers=api_headers(), json=packet, timeout=HTTP_TIMEOUT
    )

    if response.status_code not in (200, 201):
        raise RuntimeError(f"HTTP {response.status_code}: {response.text}")


# ============================================================
# MAIN PROGRAM
# ============================================================


def main():

    if "PASTE_YOUR_API_KEY_HERE" in API_KEY:
        print("ERROR:")
        print("Paste your SmartManagement API key first.")
        return

    # Check website/API first
    try:
        check_api()

    except Exception as error:
        print("API ERROR:", error)
        return

    while True:
        board = None

        try:
            board, pir, ldr, lm35 = connect_arduino()

            while True:
                sensor_data = read_sensors(pir, ldr, lm35)

                if sensor_data is None:
                    print("Waiting for sensor data...")
                    time.sleep(0.5)
                    continue

                motion, light, temperature_c = sensor_data

                packet = create_packet(motion, light, temperature_c)

                print(
                    f"Motion: {int(motion)} | "
                    f"Light: {light:4d} | "
                    f"Temperature: {temperature_c:.2f} °C | "
                    f"Status: {packet['status']}"
                )

                try:
                    upload_data(packet)

                    print("  -> Uploaded to SmartManagement")

                except requests.RequestException as error:
                    print("  -> Internet/API connection error:", error)

                except RuntimeError as error:
                    print("  -> API error:", error)

                time.sleep(UPLOAD_INTERVAL)

        except KeyboardInterrupt:
            print()
            print("Program stopped.")

            if board is not None:
                try:
                    board.exit()
                except:
                    pass

            break

        except Exception as error:
            print()
            print("Arduino / HC-06 DISCONNECTED:", error)

            if board is not None:
                try:
                    board.exit()
                except:
                    pass

            print("Telemetry upload stopped.")

            print("SmartManagement will automatically show DISCONNECTED.")

            print(f"Trying again in {RECONNECT_DELAY} seconds...")

            time.sleep(RECONNECT_DELAY)


# ============================================================
# START
# ============================================================

if __name__ == "__main__":
    main()
