#!/usr/bin/env python3
"""
HRC Vehicle Seat LIVE_DEVICE Demo Template
Runtime: HRC v0.3.1

Replace HRC_LICENSE_KEY with a tenant key issued by GNX.
This template demonstrates:
- tenant-licensed LIVE_DEVICE session start
- HMAC-SHA256 signed packet
- HRC decision response
"""

import copy
import hashlib
import hmac
import json
import math
import time
import urllib.request

BASE_URL = "https://somatosophy.com"
TARGET_PROFILE = "vehicle_seat"
LICENSE_KEY = "hrclic_REPLACE_WITH_PARTNER_VEHICLE_SEAT_KEY"

def canonical(obj):
    return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(",", ":"))

def sign_packet(packet, license_key):
    pkt = copy.deepcopy(packet)
    pkt["integrity"].pop("signature", None)
    msg = canonical(pkt)
    return hmac.new(license_key.encode(), msg.encode(), hashlib.sha256).hexdigest()

def post(path, payload):
    req = urllib.request.Request(
        BASE_URL + path,
        data=json.dumps(payload, ensure_ascii=False).encode(),
        headers={"Content-Type": "application/json"},
        method="POST"
    )
    with urllib.request.urlopen(req, timeout=15) as res:
        return json.loads(res.read().decode())

def start_session():
    return post("/api/session/start", {
        "target_profile": TARGET_PROFILE,
        "input_source": "LIVE_DEVICE",
        "license_key": LICENSE_KEY
    })

def build_packet(session_id, tick):
    bio_phase = (tick * 0.25 * 2 * math.pi * 0.10) % (2 * math.pi)
    stimulus_phase = bio_phase - 0.08

    packet = {
        "source_type": "LIVE_DEVICE",
        "interval_ms": 250,
        "bio_phase_rad": bio_phase,
        "stimulus_phase_rad": stimulus_phase,
        "heart_rate_bpm": 68.0,
        "hrv_rmssd_ms": 39.0,
        "respiration_phase_rad": bio_phase,
        "quality_score": 0.93,
        "actuator_latency_ms": 20,
        "integrity": {
            "device_id": "vehicle-seat-dev-001",
            "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "nonce": hashlib.sha256(f"{time.time()}-{tick}".encode()).hexdigest()[:24],
            "session_id": session_id,
            "signature_alg": "HMAC-SHA256"
        }
    }
    packet["integrity"]["signature"] = sign_packet(packet, LICENSE_KEY)
    return packet

def main():
    started = start_session()
    session_id = started["session"]["session_id"]
    print("session:", session_id)

    for tick in range(10):
        packet = build_packet(session_id, tick)
        result = post("/api/session/step", {
            "session_id": session_id,
            "packet": packet
        })
        d = result["decision"]
        print(json.dumps({
            "tick": d["tick"],
            "state": d["state"],
            "policy": d["actuation_policy"],
            "phase_error": d["phase"]["abs_phase_error_rad"],
            "evidence_hash": d["evidence_hash"]
        }, ensure_ascii=False))

if __name__ == "__main__":
    main()
