/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.apache.spark.sql.comet

import org.apache.spark.rdd.RDD
import org.apache.spark.sql.catalyst.InternalRow
import org.apache.spark.sql.catalyst.expressions.Expression
import org.apache.spark.sql.catalyst.plans.QueryPlan
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.errors.QueryExecutionErrors
import org.apache.spark.sql.execution.{BaseSubqueryExec, SparkPlan, UnaryExecNode}

/**
 * Preserves SubqueryAdaptiveBroadcastExec data through Spark's PlanAdaptiveDynamicPruningFilters
 * rule.
 *
 * Spark's PlanAdaptiveDynamicPruningFilters (queryStageOptimizerRule) pattern-matches on
 * SubqueryAdaptiveBroadcastExec. When it can't find a matching BroadcastHashJoinExec (because
 * Comet replaced it with CometBroadcastHashJoinExec), it replaces the DPP expression with
 * Literal.TrueLiteral, disabling DPP entirely.
 *
 * CometExecRule wraps SABs in this class during queryStagePreparationRules (before
 * queryStageOptimizerRules run). Spark's rule won't match this type. Then
 * CometPlanAdaptiveDynamicPruningFilters (a custom queryStageOptimizerRule) unwraps the SAB data
 * and converts it to CometSubqueryBroadcastExec with the join's BroadcastQueryStageExec for true
 * broadcast reuse.
 *
 * Not executable - must be converted before execution.
 */
case class CometSubqueryAdaptiveBroadcastExec(
    name: String,
    indices: Seq[Int],
    onlyInBroadcast: Boolean,
    @transient buildPlan: LogicalPlan,
    buildKeys: Seq[Expression],
    child: SparkPlan)
    extends BaseSubqueryExec
    with UnaryExecNode {

  // This node must be converted to CometSubqueryBroadcastExec by
  // CometPlanAdaptiveDynamicPruningFilters before execution. If we reach doExecute(),
  // the rule didn't run (e.g., Spark 3.4 where injectQueryStageOptimizerRule is unavailable).
  protected override def doExecute(): RDD[InternalRow] = {
    throw QueryExecutionErrors.executeCodePathUnsupportedError(
      "CometSubqueryAdaptiveBroadcastExec (should have been converted by " +
        "CometPlanAdaptiveDynamicPruningFilters)")
  }

  protected override def doCanonicalize(): SparkPlan = {
    val keys = buildKeys.map(k => QueryPlan.normalizeExpressions(k, child.output))
    copy(name = "dpp", buildKeys = keys, child = child.canonicalized)
  }

  override protected def withNewChildInternal(
      newChild: SparkPlan): CometSubqueryAdaptiveBroadcastExec =
    copy(child = newChild)
}
