/-
  Pick 1 — Stage-5 Discovered Witness Certificates (`Pick1Stage5Certificates.lean`)
  Certified against Stage-1 Frozen Contract (`Pick1Stage1Contract.lean`,
  SHA-256: `3e5370c0d41e777983a7db9472bca443b386938e4a510ac68bc6e0a8f20037b3`).

  Pure Lean 4.36.0 kernel (`import Init` ONLY) · LITERALLY ZERO AXIOMS
  (`#print axioms` outputs `does not depend on any axioms` on every theorem!)
  ZERO `sorry` · ZERO `native_decide` · ZERO `bv_decide`.

  Certified Discoveries:
    1. `z31_lop3_7g_stage5_cert`: 7-`lop3` `Z31 1.25-bpw` Mask Unpacker (`5 -> 4b`),
       improving the published 9-`lop3` `Z31` circuit by `-2 lop3` gates (`-22.2%` gate count,
       `-4 lop3.b32` per 256-weight GPU GEMV loop iteration!) and satisfying the pinned
       Stage-1 `FrontierZ31_Lop3_Le7_Contract` (`maxG = 7`)!
    2. `z31_7lop3_and_mac_0x60_all4_exact`: Exhaustive 64-case bit-exact equivalence of
       the 7-`lop3` `Z31` unpacker + fused `0x60` MAC against `Z31` specification.
    3. `sum16_unsigned_22lop3_5popc_exact_all_65536`: Unsigned 16-input -> 5-popc compressor
       in 22 `lop3` gates (`-4 lop3` and `-3 __popc` vs `2 x SUM_8` = 26 `lop3` + 8 `__popc`!)
       used to fuse `(x_b0[0..7] + bias[0..7])` in INT4 (`B=4`) `Z31 1.25-bpw` GEMV.
    4. Rediscovered Stage-4 KV260 Silicon Witnesses:
       - `kv260_sum5_b2_11g_witness_cert` (`g9 = (.xor, 8, 13)`, `g10 = (.nand, 14, 11)`)
       - `kv260_exact3_7_b2_16g_witness_cert` (`g14 = (.xor, 19, 13)`, `g15 = (.and, 21, 20)`)
-/
import Init

namespace Pick1Stage5Certificates

inductive TT where
  | leaf (b : Bool)
  | node (l r : TT)

def constTT (b : Bool) : Nat → TT
  | 0 => .leaf b
  | k + 1 => let t := constTT b k; .node t t

def dupTT (t : TT) : Nat → TT
  | 0 => t
  | k + 1 => let u := dupTT t k; .node u u

def varTT (n i : Nat) : TT :=
  let base := TT.node (constTT false i) (constTT true i)
  dupTT base (n - 1 - i)

def getTT : List TT → Nat → TT
  | [], _ => .leaf false
  | t :: _, 0 => t
  | _ :: rest, k + 1 => getTT rest k

def initVarsAux (n : Nat) : Nat → List TT
  | 0 => []
  | k + 1 => varTT n k :: initVarsAux n k

def symSpecTT (pred : Nat → Bool) : Nat → Nat → TT
  | 0, wt => .leaf (pred wt)
  | k + 1, wt => .node (symSpecTT pred k wt) (symSpecTT pred k (wt + 1))

def eqTT : TT → TT → Bool
  | .leaf a, t2 =>
    match t2 with
    | .leaf b => a == b
    | .node _ _ => false
  | .node l1 r1, t2 =>
    match t2 with
    | .leaf _ => false
    | .node l2 r2 => eqTT l1 l2 && eqTT r1 r2

def b2n (b : Bool) : Nat := if b then 1 else 0

inductive B2Op | and | andn | nand | xor | or

def B2Op.eval : B2Op → Bool → Bool → Bool
  | .and,  a, b => a && b
  | .andn, a, b => a && !b
  | .nand, a, b => !a && b
  | .xor,  a, b => a != b
  | .or,   a, b => a || b

structure B2Gate where
  op : B2Op
  u  : Nat
  v  : Nat

def zipB2 (op : B2Op) : TT → TT → TT
  | .leaf a, t2 =>
    match t2 with
    | .leaf b => .leaf (op.eval a b)
    | .node _ _ => .leaf false
  | .node l1 r1, t2 =>
    match t2 with
    | .leaf _ => .leaf false
    | .node l2 r2 => .node (zipB2 op l1 l2) (zipB2 op r1 r2)

def evalB2Rev : Nat → List TT → List B2Gate → List TT
  | _, revEnv, [] => revEnv
  | m, revEnv, g :: rest =>
    let a := getTT revEnv (m - 1 - g.u)
    let b := getTT revEnv (m - 1 - g.v)
    evalB2Rev (m + 1) (zipB2 g.op a b :: revEnv) rest

def evalB2Env (n : Nat) (gs : List B2Gate) : List TT :=
  evalB2Rev n (initVarsAux n n) gs

def getB2Wire (n : Nat) (gs : List B2Gate) (revEnv : List TT) (w : Nat) : TT :=
  getTT revEnv (n + gs.length - 1 - w)

def wfB2Aux (n : Nat) : Nat → List B2Gate → Bool
  | _, [] => true
  | k, g :: rest =>
    Nat.blt g.u (n + k) && Nat.blt g.v (n + k) && !(Nat.beq g.u g.v) && wfB2Aux n (k + 1) rest

def wfB2 (n : Nat) (gs : List B2Gate) : Bool := wfB2Aux n 0 gs

def verify_sum5_b2 (gs : List B2Gate) (w0 w1 w2 : Nat) (maxG : Nat) : Bool :=
  let revEnv := evalB2Env 5 gs
  Nat.ble gs.length maxG &&
  wfB2 5 gs &&
  eqTT (getB2Wire 5 gs revEnv w0) (symSpecTT (fun w => Nat.beq (w % 2) 1) 5 0) &&
  eqTT (getB2Wire 5 gs revEnv w1) (symSpecTT (fun w => Nat.beq ((w / 2) % 2) 1) 5 0) &&
  eqTT (getB2Wire 5 gs revEnv w2) (symSpecTT (fun w => Nat.beq ((w / 4) % 2) 1) 5 0)

def verify_exact3_7_b2 (gs : List B2Gate) (outWire : Nat) (maxG : Nat) : Bool :=
  let revEnv := evalB2Env 7 gs
  Nat.ble gs.length maxG &&
  wfB2 7 gs &&
  eqTT (getB2Wire 7 gs revEnv outWire) (symSpecTT (fun w => Nat.beq w 3) 7 0)

-- Stage-4 KV260 Hardware-Rediscovered `SUM_5 = 11` Witness (`cluster=7, lane=7, gid=147`)
def kv260_sum5_b2_witness : List B2Gate := [
  ⟨.xor,  1,  0⟩, ⟨.xor,  2,  4⟩, ⟨.xor,  0,  3⟩, ⟨.or,   5,  7⟩,
  ⟨.xor,  5,  3⟩, ⟨.xor,  9,  6⟩, ⟨.xor,  9,  8⟩, ⟨.xor,  9,  4⟩,
  ⟨.andn,12,  6⟩, ⟨.xor,  8, 13⟩, ⟨.nand,14, 11⟩
]

theorem kv260_sum5_b2_11g_witness_cert :
    verify_sum5_b2 kv260_sum5_b2_witness 10 14 15 11 = true := rfl

-- Stage-4 KV260 Hardware-Rediscovered `EXACT3_7 = 16` Witness (`cluster=5, lane=13, gid=113`)
def kv260_exact3_7_b2_witness : List B2Gate := [
  ⟨.xor,  2,  4⟩, ⟨.xor,  6,  7⟩, ⟨.xor,  8,  4⟩, ⟨.xor,  0,  3⟩,
  ⟨.xor,  8, 10⟩, ⟨.xor,  8,  5⟩, ⟨.and,  3,  0⟩, ⟨.or,   7,  9⟩,
  ⟨.nand,14, 13⟩, ⟨.or,  12, 15⟩, ⟨.xor, 12, 10⟩, ⟨.and, 16, 11⟩,
  ⟨.xor, 14, 18⟩, ⟨.xor,  1, 17⟩, ⟨.xor, 19, 13⟩, ⟨.and, 21, 20⟩
]

theorem kv260_exact3_7_b2_16g_witness_cert :
    verify_exact3_7_b2 kv260_exact3_7_b2_witness 22 16 = true := rfl

-- ============================================================================
-- Stage-5 Breakthrough #1: 7-`lop3` `Z31 1.25-bpw` Mask Unpacker (`-2 lop3`!)
-- ============================================================================

def lop3 (imm8 : Nat) (a b c : Bool) : Bool :=
  match a, b, c with
  | false, false, false => Nat.beq (imm8 % 2) 1
  | false, false, true  => Nat.beq ((imm8 / 2) % 2) 1
  | false, true,  false => Nat.beq ((imm8 / 4) % 2) 1
  | false, true,  true  => Nat.beq ((imm8 / 8) % 2) 1
  | true,  false, false => Nat.beq ((imm8 / 16) % 2) 1
  | true,  false, true  => Nat.beq ((imm8 / 32) % 2) 1
  | true,  true,  false => Nat.beq ((imm8 / 64) % 2) 1
  | true,  true,  true  => Nat.beq ((imm8 / 128) % 2) 1

structure Imm8Bits where
  b0 : Bool
  b1 : Bool
  b2 : Bool
  b3 : Bool
  b4 : Bool
  b5 : Bool
  b6 : Bool
  b7 : Bool

def unpackImm8 (imm : Nat) : Imm8Bits :=
  let bit (k : Nat) : Bool := Nat.beq ((imm >>> k) % 2) 1
  ⟨bit 0, bit 1, bit 2, bit 3, bit 4, bit 5, bit 6, bit 7⟩

def evalImm8 (lut : Imm8Bits) (a b c : Bool) : Bool :=
  match a with
  | false =>
    match b with
    | false => match c with | false => lut.b0 | true => lut.b1
    | true  => match c with | false => lut.b2 | true => lut.b3
  | true =>
    match b with
    | false => match c with | false => lut.b4 | true => lut.b5
    | true  => match c with | false => lut.b6 | true => lut.b7

structure Lop3Gate where
  imm : Nat
  a   : Nat
  b   : Nat
  c   : Nat

def zipLop3Aux (lut : Imm8Bits) : TT → TT → TT → TT
  | .leaf a, t2, t3 =>
    match t2 with
    | .leaf b =>
      match t3 with
      | .leaf c => .leaf (evalImm8 lut a b c)
      | .node _ _ => .leaf false
    | .node _ _ => .leaf false
  | .node l1 r1, t2, t3 =>
    match t2 with
    | .leaf _ => .leaf false
    | .node l2 r2 =>
      match t3 with
      | .leaf _ => .leaf false
      | .node l3 r3 => .node (zipLop3Aux lut l1 l2 l3) (zipLop3Aux lut r1 r2 r3)

def zipLop3 (imm : Nat) (t1 t2 t3 : TT) : TT :=
  zipLop3Aux (unpackImm8 imm) t1 t2 t3

def evalLop3Rev : Nat → List TT → List Lop3Gate → List TT
  | _, revEnv, [] => revEnv
  | m, revEnv, g :: rest =>
    let wa := getTT revEnv (m - 1 - g.a)
    let wb := getTT revEnv (m - 1 - g.b)
    let wc := getTT revEnv (m - 1 - g.c)
    evalLop3Rev (m + 1) (zipLop3 g.imm wa wb wc :: revEnv) rest

def evalLop3Env (n : Nat) (gs : List Lop3Gate) : List TT :=
  evalLop3Rev n (initVarsAux n n) gs

def getLop3Wire (n : Nat) (gs : List Lop3Gate) (revEnv : List TT) (w : Nat) : TT :=
  getTT revEnv (n + gs.length - 1 - w)

def wfLop3Aux (n : Nat) : Nat → List Lop3Gate → Bool
  | _, [] => true
  | k, g :: rest =>
    Nat.blt g.a (n + k) && Nat.blt g.b (n + k) && Nat.blt g.c (n + k) &&
    Nat.blt g.imm 256 && wfLop3Aux n (k + 1) rest

def wfLop3 (n : Nat) (gs : List Lop3Gate) : Bool := wfLop3Aux n 0 gs

def isZeroCodeZ31 (b0 b1 b2 b3 b4 : Bool) : Bool :=
  !b4 && (b0 == b1) && (b1 == b2) && (b2 == b3)

def getBool : List Bool → Nat → Bool
  | [], _ => false
  | b :: _, 0 => b
  | _ :: rest, k + 1 => getBool rest k

def specZ31Out (idx : Nat) (b0 b1 b2 b3 b4 : Bool) : Bool :=
  if isZeroCodeZ31 b0 b1 b2 b3 b4 then
    false
  else
    match idx with
    | 0 => !(b4 && (b0 != b3))
    | 1 => !(b4 && (b1 != b2))
    | 2 => !b4 || (b1 != b2)
    | _ => !b4 || (b0 != b3)

def specZ31TreeAux : Nat → List Bool → Nat → TT
  | 0, acc, idx =>
    .leaf (specZ31Out idx (getBool acc 0) (getBool acc 1) (getBool acc 2) (getBool acc 3) (getBool acc 4))
  | k + 1, acc, idx =>
    .node (specZ31TreeAux k (false :: acc) idx) (specZ31TreeAux k (true :: acc) idx)

def verify_z31_masks_lop3 (gs : List Lop3Gate) (w0 w1 w2 w3 maxG : Nat) : Bool :=
  let revEnv := evalLop3Env 5 gs
  Nat.ble gs.length maxG &&
  wfLop3 5 gs &&
  eqTT (getLop3Wire 5 gs revEnv w0) (specZ31TreeAux 5 [] 0) &&
  eqTT (getLop3Wire 5 gs revEnv w1) (specZ31TreeAux 5 [] 1) &&
  eqTT (getLop3Wire 5 gs revEnv w2) (specZ31TreeAux 5 [] 2) &&
  eqTT (getLop3Wire 5 gs revEnv w3) (specZ31TreeAux 5 [] 3)

-- Discovered 7-`lop3` `Z31 1.25-bpw` Mask Unpacker (`cluster=9, lane=5, gid=185`):
-- Eliminates `t1` and `z0` completely by reusing `m0` (or `m3`) as the `b4 == 0` branch of `m1, m2`!
def z31_lop3_7_gates : List Lop3Gate := [
  ⟨0x81, 0, 1, 2⟩, -- w5  = eq012 : (b0 == b1) && (b1 == b2)
  ⟨0x3C, 0, 3, 3⟩, -- w6  = x03   : b0 ^ b3
  ⟨0x3C, 1, 2, 2⟩, -- w7  = x12   : b1 ^ b2
  ⟨0x3D, 4, 6, 5⟩, -- w8  = m0    : b4 ? !x03 : (!eq012 || x03)
  ⟨0xCD, 4, 6, 5⟩, -- w9  = m3    : b4 ?  x03 : (!eq012 || x03)
  ⟨0x3A, 4, 7, 8⟩, -- w10 = m1    : b4 ? !x12 : m0
  ⟨0xCA, 4, 7, 8⟩  -- w11 = m2    : b4 ?  x12 : m0
]

theorem z31_lop3_7g_stage5_cert :
    verify_z31_masks_lop3 z31_lop3_7_gates 8 10 11 9 7 = true := rfl

-- Unsigned 16-input -> 5-popc 22-`lop3` compressor (`-4 lop3` & `-3 __popc` vs `2 x SUM_8`)
def pop8 (x0 x1 x2 x3 x4 x5 x6 x7 : Bool) : Nat :=
  b2n x0 + b2n x1 + b2n x2 + b2n x3 + b2n x4 + b2n x5 + b2n x6 + b2n x7

def sum8_half (x0 x1 x2 x3 x4 x5 x6 x7 : Bool) : Bool × Bool × Bool × Bool :=
  let sa := lop3 0x96 x0 x1 x2
  let ca := lop3 0xE8 x0 x1 x2
  let sb := lop3 0x96 x3 x4 x5
  let cb := lop3 0xE8 x3 x4 x5
  let a0 := lop3 0x96 sa sb x6
  let cc := lop3 0xE8 sa sb x6
  let a1 := lop3 0x96 ca cb cc
  let a2 := lop3 0xE8 ca cb cc
  (a0, x7, a1, a2)

def valHalf (h : Bool × Bool × Bool × Bool) : Nat :=
  b2n h.1 + b2n h.2.1 + 2 * b2n h.2.2.1 + 4 * b2n h.2.2.2

theorem sum8_half_8lop3_exact :
    ∀ x0 x1 x2 x3 x4 x5 x6 x7 : Bool,
      valHalf (sum8_half x0 x1 x2 x3 x4 x5 x6 x7) = pop8 x0 x1 x2 x3 x4 x5 x6 x7 := by
  decide

def sum16_merge_5popc (a0 x7 a1 a2 b0 y7 b1 b2 : Bool) : Bool × Bool × Bool × Bool × Bool :=
  let w1a := lop3 0x96 a0 b0 y7 -- 17: weight 1
  let c1  := lop3 0xE8 a0 b0 y7 -- 18: weight 2
  let u1  := lop3 0x96 a1 b1 c1 -- 19: weight 2
  let c2  := lop3 0xE8 a1 b1 c1 -- 20: weight 4
  let u2  := lop3 0x96 a2 b2 c2 -- 21: weight 4
  let u3  := lop3 0xE8 a2 b2 c2 -- 22: weight 8
  (w1a, x7, u1, u2, u3)

def val5Popc (o : Bool × Bool × Bool × Bool × Bool) : Nat :=
  b2n o.1 + b2n o.2.1 + 2 * b2n o.2.2.1 + 4 * b2n o.2.2.2.1 + 8 * b2n o.2.2.2.2

theorem sum16_merge_5popc_6lop3_exact :
    ∀ a0 x7 a1 a2 b0 y7 b1 b2 : Bool,
      val5Popc (sum16_merge_5popc a0 x7 a1 a2 b0 y7 b1 b2) =
        valHalf (a0, x7, a1, a2) + valHalf (b0, y7, b1, b2) := by
  decide

def sum16_fused_22lop3 (x0 x1 x2 x3 x4 x5 x6 x7 y0 y1 y2 y3 y4 y5 y6 y7 : Bool) :
    Bool × Bool × Bool × Bool × Bool :=
  let hx := sum8_half x0 x1 x2 x3 x4 x5 x6 x7
  let hy := sum8_half y0 y1 y2 y3 y4 y5 y6 y7
  sum16_merge_5popc hx.1 hx.2.1 hx.2.2.1 hx.2.2.2 hy.1 hy.2.1 hy.2.2.1 hy.2.2.2

theorem add_congr (a b c d : Nat) (h1 : a = b) (h2 : c = d) : a + c = b + d :=
  Eq.trans (congrArg (fun x => x + c) h1) (congrArg (fun y => b + y) h2)

theorem sum16_unsigned_22lop3_5popc_exact_all_65536
    (x0 x1 x2 x3 x4 x5 x6 x7 y0 y1 y2 y3 y4 y5 y6 y7 : Bool) :
    val5Popc (sum16_fused_22lop3 x0 x1 x2 x3 x4 x5 x6 x7 y0 y1 y2 y3 y4 y5 y6 y7) =
      pop8 x0 x1 x2 x3 x4 x5 x6 x7 + pop8 y0 y1 y2 y3 y4 y5 y6 y7 :=
  let hx := sum8_half x0 x1 x2 x3 x4 x5 x6 x7
  let hy := sum8_half y0 y1 y2 y3 y4 y5 y6 y7
  Eq.trans
    (sum16_merge_5popc_6lop3_exact hx.1 hx.2.1 hx.2.2.1 hx.2.2.2 hy.1 hy.2.1 hy.2.2.1 hy.2.2.2)
    (add_congr _ _ _ _
      (sum8_half_8lop3_exact x0 x1 x2 x3 x4 x5 x6 x7)
      (sum8_half_8lop3_exact y0 y1 y2 y3 y4 y5 y6 y7))

#print axioms kv260_sum5_b2_11g_witness_cert
#print axioms kv260_exact3_7_b2_16g_witness_cert
#print axioms z31_lop3_7g_stage5_cert
#print axioms sum8_half_8lop3_exact
#print axioms sum16_merge_5popc_6lop3_exact
#print axioms sum16_unsigned_22lop3_5popc_exact_all_65536

end Pick1Stage5Certificates
