#!/bin/sh
# CrazeCode Widget plugin · working demo
# 疯码 Widget 插件 · 可直接运行的示例
#
# The host writes two JSON lines to stdin and reads two JSON lines from stdout.
# 宿主向 stdin 写两行 JSON，并从 stdout 读两行 JSON。
#
# The sandbox forbids fork(), so this script may not use command substitution,
# pipes, or any external command such as sed, awk or jq. Shell builtins only.
# 沙箱禁止 fork()，所以本脚本不能使用命令替换、管道，或 sed/awk/jq 等外部命令，
# 只能使用 shell 内建语法。

# --- line 1 · handshake / 第一行：握手 -------------------------------------
# The host asks which protocol version and capabilities you accept.
# 宿主询问你接受哪个协议版本与能力集。
IFS= read -r handshake

printf '%s\n' '{"protocol_version":1,"request_id":"handshake","response":{"type":"handshake","selected_version":1,"capabilities":["typed_value"],"permissions":["widget_identity"]}}'

# --- line 2 · refresh / 第二行：刷新 ---------------------------------------
# The refresh request carries attempt_revision. You MUST echo that exact number
# back as value.revision, or the host rejects the value as InvalidValue on
# every refresh after the first one.
# 刷新请求里带着 attempt_revision。你必须把这个数字原样回填到 value.revision，
# 否则从第二次刷新开始，宿主会以 InvalidValue 拒绝你的返回值。
IFS= read -r refresh

rest=${refresh#*\"attempt_revision\":}
revision=${rest%%,*}
revision=${revision%%\}*}

# Replace this with whatever your widget should show.
# 把这里换成你的 Widget 想显示的内容。
value=42

printf '{"protocol_version":1,"request_id":"refresh","response":{"type":"value","value":{'
printf '"schema_version":1,"widget_id":"w-demo","revision":%s,' "$revision"
printf '"kind":"metric","title":"Demo","updated_at_ms":0,"fresh_until_ms":0,'
printf '"status":"ok","summary":{"value":"%s"},' "$value"
printf '"data":{"value":"%s","unit":null,"change":null},' "$value"
printf '"actions":[],"provenance":{"provider_id":"p-demo","source_class":"plugin"},'
printf '"truncated":false}}}\n'
