"""A linked stack: each node owns the next (the ownership corpus, in Vibe)."""

from dataclasses import dataclass

from verada import Owned, ensures, move, requires


@dataclass
class Node:
    value: int
    next: Owned[Node] | None = None


@dataclass
class Stack:
    head: Owned[Node] | None = None

    def push(self, x: int) -> None:
        ensures(self.head is not None)
        # the old head moves into the new node
        self.head = Owned(Node(value=x, next=self.head))

    def pop(self) -> int:
        requires(self.head is not None)
        n = move(self.head)
        self.head = n.next
        x = n.value
        del n
        return x

    # every node freed, one by one
    def clear(self) -> None:
        ensures(self.head is None)
        while self.head is not None:
            n = move(self.head)
            self.head = n.next
            del n
