class Value:
    """ 
    存储单个标量值及其梯度。
    它是计算图中的一个节点。
    """

    def __init__(self, data, _children=(), _op=''):
        self.data = data    # 节点存储的实际数值（前向传播的结果）
        self.grad = 0       # 损失函数对该节点的导数（初始为0，反向传播时计算）
        
        # 内部变量，用于自动求导图的构建
        # _backward 是一个函数，定义了如何将“输出端的梯度”传递给“输入端的节点”
        self._backward = lambda: None 
        
        # 存储产生该节点的父节点（即当前的输入节点）
        self._prev = set(_children) 
        
        # 产生该节点的运算符（用于调试和可视化，如 '+', '*', 'ReLU'）
        self._op = _op 

    def __add__(self, other):
        """ 加法运算：self + other """
        # 如果 other 不是 Value 类型（例如是一个整数），则将其转换为 Value
        other = other if isinstance(other, Value) else Value(other)
        
        # 前向传播：计算加法结果，并记录子节点和运算符
        out = Value(self.data + other.data, (self, other), '+')

        def _backward():
            """ 
            加法的反向传播逻辑：
            根据微积分：f(x,y) = x + y，则 df/dx = 1, df/dy = 1。
            根据链式法则：当前节点的梯度 = 输出节点的梯度 * 局部导数(1)。
            注意使用 += 是为了处理同一个变量被多次使用的情况（梯度累加）。
            """
            self.grad += out.grad
            other.grad += out.grad
        
        # 将该逻辑绑定到输出节点的 _backward 属性上
        out._backward = _backward

        return out

    def __mul__(self, other):
        """ 乘法运算：self * other """
        other = other if isinstance(other, Value) else Value(other)
        
        # 前向传播：计算乘法结果
        out = Value(self.data * other.data, (self, other), '*')

        def _backward():
            """
            乘法的反向传播逻辑：
            根据微积分：f(x,y) = x * y，则 df/dx = y, df/dy = x。
            链式法则：
            self 的梯度 = 输出梯度 * other 的数值
            other 的梯度 = 输出梯度 * self 的数值
            """
            self.grad += other.data * out.grad
            other.grad += self.data * out.grad
        out._backward = _backward

        return out

    def __pow__(self, other):
        """ 幂运算：self ** other (仅支持数值指数) """
        assert isinstance(other, (int, float)), "目前仅支持整数或浮点数幂运算"
        out = Value(self.data**other, (self,), f'**{other}')

        def _backward():
            """
            幂函数的导数：d(x^n)/dx = n * x^(n-1)。
            """
            self.grad += (other * self.data**(other-1)) * out.grad
        out._backward = _backward

        return out

    def relu(self):
        """ ReLU 激活函数：max(0, x) """
        out = Value(0 if self.data < 0 else self.data, (self,), 'ReLU')

        def _backward():
            """
            ReLU 的导数：如果输入 > 0，导数为 1；如果输入 <= 0，导数为 0。
            """
            self.grad += (out.data > 0) * out.grad
        out._backward = _backward

        return out

    

    def backward(self):
        """ 
        启动反向传播：
        从当前节点开始，自动计算计算图中所有节点的梯度。
        """

        # 1. 拓扑排序：确保在计算某个节点的梯度之前，所有依赖它的节点都已经计算完了梯度。
        # 这是一个有向无环图 (DAG) 的遍历。
        topo = []
        visited = set()
        def build_topo(v):
            if v not in visited:
                visited.add(v)
                for child in v._prev:
                    build_topo(child)
                topo.append(v)
        build_topo(self)

        

        # 2. 应用链式法则：
        # 将损失函数对自身的梯度设为 1（即 dL/dL = 1）
        self.grad = 1
        # 按照拓扑排序的逆序（从输出到输入）依次调用每个节点的 _backward 函数
        for v in reversed(topo):
            v._backward()

    # --- 以下是运算符重载，让 Value 对象用起来像普通数字 ---

    def __neg__(self): # 定义 -self (取负)
        return self * -1

    def __radd__(self, other): # 定义 other + self (当左侧是常数时触发)
        return self + other

    def __sub__(self, other): # 定义 self - other
        return self + (-other)

    def __rsub__(self, other): # 定义 other - self
        return other + (-self)

    def __rmul__(self, other): # 定义 other * self (当左侧是常数时触发)
        return self * other

    def __truediv__(self, other): # 定义 self / other
        return self * other**-1

    def __rtruediv__(self, other): # 定义 other / self
        return other * self**-1

    def __repr__(self):
        """ 打印对象时的显示格式 """
        return f"Value(data={self.data}, grad={self.grad})"