{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "$id": "https://txng.theio.vn/developers/downloads/envelope-v1.schema.json",
  "title": "AgriTrace IoT envelope v1",
  "description": "Every message a device or gateway sends upstream. Signature covers the canonical JSON (sorted keys, no whitespace, UTF-8) of the envelope without the 'sig' member.",
  "type": "object",
  "required": ["spec", "id", "kind", "device", "time", "seq", "readings"],
  "properties": {
    "spec": {"const": "agritrace.iot/1.0"},
    "id": {"type": "string", "format": "uuid", "description": "Globally unique; receivers deduplicate on it."},
    "kind": {"enum": ["telemetry", "event", "status"]},
    "eventType": {"type": "string", "description": "Required when kind = event; key of event-types vocabulary."},
    "device": {
      "type": "object",
      "required": ["id", "profile"],
      "properties": {
        "id": {"type": "string"},
        "profile": {"type": "string", "description": "<profile id>@<profile version>"},
        "fw": {"type": "string"},
        "gateway": {"type": "string"}
      }
    },
    "time": {"type": "string", "format": "date-time", "description": "When the measurement happened, with UTC offset."},
    "seq": {"type": "integer", "minimum": 0, "description": "Monotonic per device; gaps reveal lost or deleted records."},
    "context": {
      "type": "object",
      "properties": {
        "lot": {"type": "string"},
        "gtin": {"type": "string"},
        "parcel": {"type": "string", "description": "Parcel id in the national land database, or verified self-declared id."},
        "growing_area": {"type": "string", "description": "Ma so vung trong."},
        "facility": {"type": "string", "description": "Ma co so dong goi / collection point id."},
        "operator": {"type": "string"},
        "producer": {"type": "string", "description": "Farmer / household id."},
        "epoch": {"type": "string", "description": "The latest server epoch value the device fetched (GET /v1/public/epoch, field `epoch`: 32 lower-case hex digits; a new signed value every hour). Optional. A reading cannot have been signed before the value it cites was issued, so ingest flags (never rejects) an envelope whose value is unknown to the server, issued after a reading's time, or older than the allowed window (default 24 hours) at a reading's time; each flagged reading is Self-declared (reason server_epoch_mismatch)."},
        "signer": {"enum": ["device", "gateway"], "description": "Whose key signed the envelope: the device's own key, or a gateway's key on behalf of a device that cannot sign (for example a LoRaWAN sensor received through a network server). Optional. When present, ingest checks it against the owner of the signing key and holds an envelope whose claim differs for review (reason signer_mismatch). A gateway-signed reading says that the gateway received and recorded it, not that the sensor signed it."}
      },
      "additionalProperties": {"type": "string"}
    },
    "readings": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["capability", "value"],
        "properties": {
          "capability": {"type": "string"},
          "value": {},
          "unit": {"type": "string"},
          "quality": {"enum": ["good", "uncertain", "bad"]},
          "time": {"type": "string", "format": "date-time"},
          "meta": {"type": "object"}
        },
        "if": {"required": ["capability"], "properties": {"capability": {"const": "geo.position"}}},
        "then": {"properties": {"meta": {"$ref": "#/$defs/geoPositionMeta"}}}
      }
    },
    "attachments": {
      "type": "array",
      "items": {
        "type": "object",
        "required": ["mediaType", "sha256"],
        "properties": {
          "mediaType": {"type": "string"},
          "sha256": {"type": "string", "pattern": "^[0-9a-f]{64}$"},
          "uri": {"type": "string"},
          "size": {"type": "integer"}
        }
      }
    },
    "sig": {
      "type": "object",
      "required": ["alg", "kid", "value"],
      "properties": {
        "alg": {"enum": ["ES256"]},
        "kid": {"type": "string"},
        "value": {"type": "string", "description": "base64url(r || s)"}
      }
    }
  },
  "if": {"properties": {"kind": {"const": "event"}}},
  "then": {"required": ["eventType", "context"]},
  "$defs": {
    "geoPositionMeta": {
      "description": "Location-quality keys of a geo.position reading's meta (capabilities 1.1.0, #226). Every key is optional; other meta keys stay free-form. The rules are those of 'meta' of geo.position in capabilities-v1.json.",
      "type": "object",
      "properties": {
        "acc_m": {"type": "number", "minimum": 0, "maximum": 10000, "description": "Horizontal accuracy in metres (68 % confidence radius)."},
        "fix": {"enum": ["2d", "3d", "dgnss", "rtk_float", "rtk_fixed"]},
        "sats": {"type": "integer", "minimum": 0, "maximum": 255, "description": "Satellites used in the fix. Write it without a fractional part (19, not 19.0): JSON Schema accepts 19.0 as an integer, but ingest quarantines it (meta.sats: expected integer, got float)."},
        "hdop": {"type": "number", "minimum": 0, "maximum": 100},
        "age_s": {"type": "number", "minimum": 0},
        "constellations": {
          "type": "array", "minItems": 1, "uniqueItems": true,
          "items": {"enum": ["gps", "galileo", "glonass", "beidou", "qzss", "navic", "sbas"]}
        },
        "cn0_mean": {"type": "number", "minimum": 0, "maximum": 100, "description": "dB-Hz"},
        "cn0_sd": {"type": "number", "minimum": 0, "maximum": 100, "description": "dB-Hz"},
        "spoof_flag": {"type": "boolean"},
        "jam_flag": {"type": "boolean"},
        "mock": {"type": "boolean"},
        "osnma": {"enum": ["authenticated", "partial", "none", "unsupported"], "description": "Reported by the device's own firmware, so not an independent source."}
      }
    }
  }
}
