"""Lab 8: Arduino Uno StandardFirmata -> HC-06 -> SmartManagement.
Tested for syntax with Python 3; intended for Python 3.8+.
"""
import inspect
import time

# Legacy pyfirmata calls inspect.getargspec, removed in Python 3.11.
# Re-create its original 4-field result using getfullargspec.
if not hasattr(inspect, "getargspec"):
    from collections import namedtuple
    ArgSpec = namedtuple("ArgSpec", "args varargs keywords defaults")

    def _getargspec(func):
        full = inspect.getfullargspec(func)
        return ArgSpec(full.args, full.varargs, full.varkw, full.defaults)

    inspect.getargspec = _getargspec

try:
    import requests
    import serial
    from pyfirmata import Arduino, util, INPUT
except ImportError as exc:
    print("Missing library:", exc)
    print("Install with: python -m pip install pyfirmata pyserial requests")
    raise SystemExit(1)

# --------------------- STUDENTS: EDIT THESE ---------------------
COM_PORT = "COM4"  # Windows Bluetooth settings -> COM Ports -> Outgoing HC-06
API_KEY = "smk_live_....." #WRITE YOUR API KEY HERE
DEVICE_NAME = "TEAM01-LAB8"
# ---------------------------------------------------------------

API_URL = "https://rasimmax.com/SmartManagement/api/v1/telemetry.php"
PING_URL = "https://rasimmax.com/SmartManagement/api/v1/ping.php"
PIR_PIN = 2
LDR_PIN = 0
DARK_THRESHOLD = 150
UPLOAD_INTERVAL = 2.0
HTTP_TIMEOUT = 5
RECONNECT_DELAY = 5
MAX_RETRIES = 3
SENSOR_START_TIMEOUT = 15


def api_headers():
    return {
        "Authorization": "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("API authentication failed: HTTP {}: {}".format(
            response.status_code, response.text[:300]))
    print("SmartManagement API: OK")


def connect_arduino():
    """Caller owns the board only after this function returns successfully."""
    print("\nConnecting to HC-06 on {}...".format(COM_PORT))
    board = None
    try:
        board = Arduino(COM_PORT, baudrate=9600)
        iterator = util.Iterator(board)
        iterator.daemon = True
        iterator.start()
        pir = board.digital[PIR_PIN]
        pir.mode = INPUT
        pir.enable_reporting()
        ldr = board.analog[LDR_PIN]
        ldr.enable_reporting()
        # COM port open does not guarantee the Arduino is sending Firmata.
        deadline = time.monotonic() + SENSOR_START_TIMEOUT
        while time.monotonic() < deadline:
            if pir.read() is not None and ldr.read() is not None:
                print("Arduino / HC-06: CONNECTED; sensor data received")
                return board, pir, ldr
            time.sleep(0.5)
        raise TimeoutError(
            "COM port opened, but no Firmata sensor data arrived. "
            "Check StandardFirmata, wiring, module baud rate and power."
        )
    except BaseException:
        if board is not None:
            try:
                board.exit()
            except Exception:
                pass
        raise


def read_sensors(pir, ldr):
    motion_value = pir.read()
    light_value = ldr.read()
    if motion_value is None or light_value is None:
        return None
    return bool(motion_value), int(light_value * 1023)


def create_packet(motion, light):
    dark = light < DARK_THRESHOLD
    if motion and dark:
        status, message = "ALERT", "Motion detected while room is dark"
    elif motion:
        status, message = "MOTION", "Motion detected"
    elif dark:
        status, message = "DARK", "Room is dark"
    else:
        status, message = "NORMAL", "Room condition is normal"
    return {
        "device": DEVICE_NAME,
        "metrics": {"motion": motion, "light": light},
        "status": status,
        "message": message,
    }


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("HTTP {}: {}".format(response.status_code,
                                                   response.text[:300]))


def main():
    if "PASTE_YOUR_API_KEY_HERE" in API_KEY or not API_KEY.strip():
        print("ERROR: Paste your SmartManagement API key first.")
        return
    try:
        check_api()
    except (requests.RequestException, RuntimeError) as exc:
        print("API ERROR:", exc)
        return

    failures = 0
    try:
        while failures < MAX_RETRIES:
            board = None
            try:
                board, pir, ldr = connect_arduino()
                failures = 0
                last_data_at = time.monotonic()
                while True:
                    sensor_data = read_sensors(pir, ldr)
                    if sensor_data is None:
                        if time.monotonic() - last_data_at > SENSOR_START_TIMEOUT:
                            raise TimeoutError("Sensor data stopped arriving")
                        print("Waiting for sensor data...")
                        time.sleep(0.5)
                        continue
                    last_data_at = time.monotonic()
                    motion, light = sensor_data
                    packet = create_packet(motion, light)
                    print("Motion: {} | Light: {:4d} | Status: {}".format(
                        int(motion), light, packet["status"]))
                    try:
                        upload_data(packet)
                        print("  -> Uploaded to SmartManagement")
                    except (requests.RequestException, RuntimeError) as exc:
                        print("  -> Internet/API error:", exc)
                    time.sleep(UPLOAD_INTERVAL)
            except serial.SerialException as exc:
                failures += 1
                print("Serial/Bluetooth error:", exc)
                if "Access is denied" in str(exc) or "PermissionError" in str(exc):
                    print("COM port is busy. Close all Python/serial programs, "
                          "disconnect/reconnect Bluetooth, then run again.")
                    return
            except PermissionError as exc:
                print("COM port access denied:", exc)
                print("Close all programs using COM4 and restart this script.")
                return
            except (TimeoutError, OSError, ValueError, AttributeError) as exc:
                failures += 1
                print("Arduino / HC-06 error:", exc)
            finally:
                if board is not None:
                    try:
                        board.exit()
                    except Exception:
                        pass
            if failures < MAX_RETRIES:
                print("Trying again in {} seconds ({}/{})...".format(
                    RECONNECT_DELAY, failures, MAX_RETRIES))
                time.sleep(RECONNECT_DELAY)
        print("Stopped after {} failed attempts. Check the Bluetooth port and Arduino.".format(MAX_RETRIES))
    except KeyboardInterrupt:
        print("\nProgram stopped by user.")


if __name__ == "__main__":
    main()
