#!/usr/bin/env python3
"""
IoT Shield – Security Camera Simulator

Generates periodic telemetry and motion events for a security camera and
forwards them to Splunk Enterprise via HEC.
"""

import json
import random
import time
from datetime import datetime

import requests
import urllib3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

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

DEVICE_ID = "camera-front-door"
DEVICE_TYPE = "security_camera"
LOCATION = "front_entrance"

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

LOG_INTERVAL_SECONDS = 5

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


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

def generate_camera_event() -> dict:
    """Generate a single security camera telemetry event."""
    timestamp = datetime.now().isoformat()
    motion_detected = random.random() < 0.30  # 30% chance of motion

    event = {
        "timestamp": timestamp,
        "device_id": DEVICE_ID,
        "device_type": DEVICE_TYPE,
        "location": LOCATION,
        "motion_detected": motion_detected,
        "recording": motion_detected,
        "resolution": "1920x1080",
        "fps": 30,
        "storage_used_gb": round(random.uniform(100, 200), 2),
        "battery_level": 100,
    }

    if motion_detected:
        event["event_type"] = "motion_alert"
        event["confidence"] = round(random.uniform(0.70, 0.99), 2)
        print(f"[ALERT] Motion detected at {timestamp}")

    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:camera",
        "index": "iot_devices",
    }

    try:
        response = requests.post(
            SPLUNK_HEC_URL,
            headers=HEADERS,
            json=payload,
            verify=False,
            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 security camera simulator indefinitely."""
    print("Starting security camera 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_camera_event()
            print(json.dumps(event, indent=2))
            send_to_splunk(event)
            time.sleep(LOG_INTERVAL_SECONDS)
        except KeyboardInterrupt:
            print("\n[INFO] Stopping camera simulator.")
            break
        except Exception as exc:
            print(f"[ERROR] Unexpected error in main loop: {exc}")
            time.sleep(LOG_INTERVAL_SECONDS)


if __name__ == "__main__":
    main()