// ops/unary.hako — NyVmOpUnary
// Accepts v1 shape: {"op":"unop","kind":"neg|not|bitnot","src":VID,"dst":VID}
// Also tolerates legacy: {"op":"unaryop","op_kind":"Neg|Not|BitNot","operand":VID,"dst":VID}
using selfhost.shared.json.core.json_cursor as JsonCursorBox
using selfhost.shared.common.string_helpers as StringHelpers
using selfhost.vm.core.state as NyVmState

static box NyVmOpUnary {
  _read_int(inst_json, key) {
    local pat = "\"" + key + "\":"
    local p = JsonCursorBox.find_key_dual(inst_json, pat, pat, 0)
    if p < 0 { return null }
    p = inst_json.indexOf(":", p)
    if p < 0 { return null }
    p = p + 1
    loop(true) { local ch = inst_json.substring(p,p+1) if ch == " " || ch == "\n" || ch == "\r" || ch == "\t" { p = p + 1 continue } break }
    local digits = JsonCursorBox.digits_from(inst_json, p)
    if digits == "" { return null }
    return StringHelpers.to_i64(digits)
  }
  _read_str(inst_json, key) {
    local pat = "\"" + key + "\":"
    local p = JsonCursorBox.find_key_dual(inst_json, pat, pat, 0)
    if p < 0 { return "" }
    p = inst_json.indexOf(":", p)
    if p < 0 { return "" }
    p = p + 1
    loop(true) { local ch = inst_json.substring(p,p+1) if ch == " " || ch == "\n" || ch == "\r" || ch == "\t" { p = p + 1 continue } break }
    if inst_json.substring(p,p+1) != "\"" { return "" }
    local end = JsonCursorBox.scan_string_end(inst_json, p)
    if end < 0 { return "" }
    return inst_json.substring(p+1, end)
  }
  handle(inst_json, state) {
    local dst = me._read_int(inst_json, "dst")
    if dst == null { print("[core/unop] missing dst") return -1 }
    // prefer v1 fields
    local src = me._read_int(inst_json, "src")
    local kind = me._read_str(inst_json, "kind")
    if src == null {
      src = me._read_int(inst_json, "operand")
      if kind == "" { kind = me._read_str(inst_json, "op_kind") }
      // normalize legacy to lower-case
      if kind == "Neg" { kind = "neg" } else if kind == "Not" { kind = "not" } else if kind == "BitNot" { kind = "bitnot" }
    }
    if src == null || kind == "" { print("[core/unop] malformed") return -1 }
    local v = NyVmState.get_reg(state, src)
    local out = 0
    if kind == "neg" { out = 0 - v }
    else if kind == "not" { out = (v == 0) ? 1 : 0 }
    else if kind == "bitnot" { out = 0 - v - 1 }
    else { print("[core/unop] unsupported kind: " + kind) return -1 }
    NyVmState.set_reg(state, dst, out)
    return 0
  }
}

static box NyVmOpUnaryMain { main(args){ return 0 } }
