#!/usr/bin/env python3
"""
IoT Shield – Smart Thermostat Simulator

Generates periodic telemetry for a smart thermostat and forwards events
to Splunk Enterprise via HTTP Event Collector (HEC).
"""

import json
import random
import time
from datetime import datetime

import requests
import urllib3

# Disable TLS warnings for lab/self-signed certificates.
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# ---------------------------------------------------------------------------
# Configuration
# ---------------------------------------------------------------------------

DEVICE_ID = "thermostat-001"
DEVICE_TYPE = "smart_thermostat"
LOCATION = "living_room"

SPLUNK_HEC_URL = "https://192.168.1.247:8088/services/collector/event"
SPLUNK_TOKEN = "a6e5158e-8a7f-455c-aee8-c18d4102e476"

LOG_INTERVAL_SECONDS = 10

HEADERS = {
    "Authorization": f"Splunk {SPLUNK_TOKEN}",
    "Content-Type": "application/json",
}


# ---------------------------------------------------------------------------
# Telemetry generation
# ---------------------------------------------------------------------------

def generate_thermostat_event() -> dict:
    """Generate a single thermostat telemetry event."""
    timestamp = datetime.now().isoformat()
    current_temp = round(random.uniform(68.0, 76.0), 1)
    target_temp = random.choice([68, 70, 72, 74])
    humidity = random.randint(30, 70)

    if current_temp < target_temp:
        hvac_status = "heating"
    elif current_temp > target_temp + 1:
        hvac_status = "cooling"
    else:
        hvac_status = "idle"

    event = {
        "timestamp": timestamp,
        "device_id": DEVICE_ID,
        "device_type": DEVICE_TYPE,
        "location": LOCATION,
        "current_temperature": current_temp,
        "target_temperature": target_temp,
        "humidity": humidity,
        "hvac_status": hvac_status,
        "battery_level": random.randint(85, 100),
        "signal_strength_dbm": random.randint(-70, -40),
    }
    return event


# ---------------------------------------------------------------------------
# Splunk forwarding
# ---------------------------------------------------------------------------

def send_to_splunk(event_data: dict) -> None:
    """Send a single event to Splunk HEC."""
    payload = {
        "event": event_data,
        "sourcetype": "iot:thermostat",
        "index": "iot_devices",
    }

    try:
        response = requests.post(
            SPLUNK_HEC_URL,
            headers=HEADERS,
            json=payload,
            verify=False,  # Accept self-signed certs in the lab
            timeout=5,
        )
        if response.status_code == 200:
            print(f"[INFO] Event sent from {event_data['device_id']}")
        else:
            print(f"[ERROR] HEC HTTP {response.status_code}: {response.text}")
    except Exception as exc:
        print(f"[ERROR] Exception while sending event: {exc}")


# ---------------------------------------------------------------------------
# Main loop
# ---------------------------------------------------------------------------

def main() -> None:
    """Run the thermostat simulator indefinitely."""
    print("Starting smart thermostat simulator")
    print(f"  Device ID  : {DEVICE_ID}")
    print(f"  HEC URL    : {SPLUNK_HEC_URL}")
    print(f"  Interval   : {LOG_INTERVAL_SECONDS} seconds")
    print("-" * 60)

    while True:
        try:
            event = generate_thermostat_event()
            print(json.dumps(event, indent=2))
            send_to_splunk(event)
            time.sleep(LOG_INTERVAL_SECONDS)
        except KeyboardInterrupt:
            print("\n[INFO] Stopping thermostat simulator.")
            break
        except Exception as exc:
            print(f"[ERROR] Unexpected error in main loop: {exc}")
            time.sleep(LOG_INTERVAL_SECONDS)


if __name__ == "__main__":
    main()