#!/usr/bin/env python3
"""
HRC Partner Adapter SDK Example
Runtime: HRC_Heart-rate Resonance Control v0.3.1

Purpose:
- Start a LIVE_DEVICE session using tenant license key.
- Create a signed LIVE packet.
- Submit the packet to /api/session/step.
- Receive HRC actuation_policy and evidence_hash.

This file is an integration reference, not a medical claim.
"""

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

BASE_URL = "https://somatosophy.com"

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

def strip_signature(packet):
    pkt = copy.deepcopy(packet)
    pkt.setdefault("integrity", {}).pop("signature", None)
    return pkt

def sign_live_packet(packet, license_key):
    msg = canonical(strip_signature(packet))
    return hmac.new(
        license_key.encode("utf-8"),
        msg.encode("utf-8"),
        hashlib.sha256
    ).hexdigest()

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

def start_live_session(license_key, target_profile="vehicle_seat"):
    return post_json("/api/session/start", {
        "target_profile": target_profile,
        "input_source": "LIVE_DEVICE",
        "license_key": license_key
    })

def build_signed_live_packet(session_id, license_key, *, bio_phase_rad, stimulus_phase_rad):
    packet = {
        "source_type": "LIVE_DEVICE",
        "interval_ms": 250,
        "bio_phase_rad": bio_phase_rad,
        "stimulus_phase_rad": stimulus_phase_rad,
        "heart_rate_bpm": 68.4,
        "hrv_rmssd_ms": 39.2,
        "respiration_phase_rad": bio_phase_rad,
        "quality_score": 0.93,
        "actuator_latency_ms": 20,
        "integrity": {
            "device_id": "partner-device-001",
            "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
            "nonce": hashlib.sha256(str(time.time()).encode()).hexdigest()[:24],
            "session_id": session_id,
            "signature_alg": "HMAC-SHA256"
        }
    }
    packet["integrity"]["signature"] = sign_live_packet(packet, license_key)
    return packet

def step(session_id, packet):
    return post_json("/api/session/step", {
        "session_id": session_id,
        "packet": packet
    })

def main():
    # Replace this with a tenant license key issued by GNX.
    license_key = "hrclic_REPLACE_WITH_PARTNER_TENANT_KEY"

    started = start_live_session(license_key)
    session_id = started["session"]["session_id"]

    pkt = build_signed_live_packet(
        session_id,
        license_key,
        bio_phase_rad=1.00,
        stimulus_phase_rad=0.92
    )

    decision = step(session_id, pkt)
    print(json.dumps(decision, ensure_ascii=False, indent=2))

if __name__ == "__main__":
    main()
