#!/usr/bin/env python3
"""
Demo runner for spoofing protections.

This script demonstrates:
 - valid HMAC telemetry passes
 - invalid HMAC is blocked
 - crazy/out-of-bounds values are blocked
 - sudden large delta (rate-of-change) is blocked
 - cross-check between driver dash and engineer dash detects subtle spoofing

Run:
  python3 tests/demo_spoofing_run.py
"""
import sys
import time

from security.spoofing_protection import SpoofingProtector, SIMULATED_SHARED_SECRET

def print_result(test_name: str, res: dict, expect_valid: bool):
    status = "PASS" if res["valid"] == expect_valid else "FAIL"
    print(f"[{status}] {test_name} -> valid={res['valid']} reason={res.get('reason')} anomaly_score={res.get('anomaly_score')}")
    if status == "FAIL":
        # If a failing check is unexpected, we exit non-zero for CI/smoke testing
        sys.exit(2)

def crosscheck_driver_engine(driver_payload: dict, engine_payload: dict, threshold_mph: float):
    """
    Simple cross-check logic: compare driver and engineer reported speeds.
    Returns (ok: bool, reason: str|None)
    """
    ds = driver_payload.get("speed_mph")
    es = engine_payload.get("speed_mph")
    if ds is None or es is None:
        return True, None
    if abs(ds - es) > threshold_mph:
        return False, f"crosscheck_delta_exceeds_threshold ({ds} vs {es})"
    return True, None

def main():
    sp = SpoofingProtector(secret=SIMULATED_SHARED_SECRET)

    # 1) Valid telemetry
    payload1 = {"speed_mph": 120, "rpm": 6000}
    tag1 = SpoofingProtector.sign(payload1, SIMULATED_SHARED_SECRET)
    res1 = sp.inspect_message("telemetry", "driver_device_01", payload1, tag1)
    print_result("Valid HMAC telemetry", res1, expect_valid=True)

    # 2) Invalid HMAC
    payload2 = {"speed_mph": 120}
    res2 = sp.inspect_message("telemetry", "driver_device_01", payload2, "BADTAG")
    print_result("Invalid HMAC telemetry", res2, expect_valid=False)

    # 3) Crazy/out-of-bounds speed
    payload3 = {"speed_mph": 3940234902, "rpm": 12345678}
    tag3 = SpoofingProtector.sign(payload3, SIMULATED_SHARED_SECRET)
    res3 = sp.inspect_message("telemetry", "driver_device_01", payload3, tag3)
    print_result("Crazy speed telemetry", res3, expect_valid=False)

    # 4) Sudden large delta (rate-of-change)
    # Feed a baseline value first
    payload4a = {"speed_mph": 150}
    tag4a = SpoofingProtector.sign(payload4a, SIMULATED_SHARED_SECRET)
    res4a = sp.inspect_message("telemetry", "driver_device_01", payload4a, tag4a)
    print_result("Baseline telemetry for ROC check", res4a, expect_valid=True)

    # Now a huge jump
    payload4b = {"speed_mph": 999}
    tag4b = SpoofingProtector.sign(payload4b, SIMULATED_SHARED_SECRET)
    res4b = sp.inspect_message("telemetry", "driver_device_01", payload4b, tag4b)
    print_result("Sudden large jump telemetry", res4b, expect_valid=False)

    # 5) Subtle spoofing cross-check (driver vs engineer)
    # Driver reports a lower value (spoofed), engineer dash has the true higher value.
    driver_payload = {"speed_mph": 270, "rpm": 6500}
    engineer_payload = {"speed_mph": 300, "rpm": 6500}
    # Both carry valid HMACs (simulation uses same secret)
    driver_tag = SpoofingProtector.sign(driver_payload, SIMULATED_SHARED_SECRET)
    engineer_tag = SpoofingProtector.sign(engineer_payload, SIMULATED_SHARED_SECRET)
    # Inspect individually: both look valid to SpoofingProtector
    r_driver = sp.inspect_message("telemetry", "driver_device_01", driver_payload, driver_tag)
    r_engineer = sp.inspect_message("telemetry", "engineer_remote_01", engineer_payload, engineer_tag)
    print_result("Subtle spoof - driver payload validity", r_driver, expect_valid=True)
    print_result("Subtle spoof - engineer payload validity", r_engineer, expect_valid=True)

    # Cross-check to detect the delta and flag it
    ok, reason = crosscheck_driver_engine(driver_payload, engineer_payload, sp.CROSSCHECK_THRESHOLD_MPH)
    if not ok:
        print(f"[DETECT] Cross-check failed: {reason}")
    else:
        print("[OK] Cross-check passed (no large delta)")

    # If we reach here, demo completed successfully.
    print("\nDemo completed successfully.")
    return 0

if __name__ == "__main__":
    sys.exit(main())
