/*
 * 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.connect.service

import com.fasterxml.jackson.annotation.JsonIgnore
import com.google.protobuf.Message

import org.apache.spark.connect.proto
import org.apache.spark.scheduler.SparkListenerEvent
import org.apache.spark.sql.catalyst.{QueryPlanningTracker, QueryPlanningTrackerCallback}
import org.apache.spark.sql.catalyst.plans.logical.LogicalPlan
import org.apache.spark.sql.connect.IllegalStateErrors
import org.apache.spark.sql.connect.common.ProtoUtils
import org.apache.spark.util.{Clock, Utils}

object ExecuteEventsManager {
  // TODO: Make this configurable
  val MAX_STATEMENT_TEXT_SIZE = 65535
  val MAX_STATEMENT_NESTING_LEVEL = 8
}

sealed abstract class ExecuteStatus(value: Int)

object ExecuteStatus {
  case object Pending extends ExecuteStatus(0)
  case object Started extends ExecuteStatus(1)
  case object Analyzed extends ExecuteStatus(2)
  case object ReadyForExecution extends ExecuteStatus(3)
  case object Finished extends ExecuteStatus(4)
  case object Failed extends ExecuteStatus(5)
  case object Canceled extends ExecuteStatus(6)
  case object Closed extends ExecuteStatus(7)
}

/**
 * Records why an operation terminated so that the reason remains available after the operation
 * transitions to the closed state.
 */
sealed abstract class TerminationReason(val value: Int)

object TerminationReason {
  case object Succeeded extends TerminationReason(0)
  case object Failed extends TerminationReason(1)
  case object Canceled extends TerminationReason(2)
}

/**
 * Manage the lifecycle of an operation by tracking its status and termination reason. Post
 * request Connect events to @link org.apache.spark.scheduler.LiveListenerBus and serve as an
 * information source for GetStatus RPC.
 *
 * {{{
 *   +---------------------------------------------+
 *   |     ExecuteEventsManager                    |
 *   |                                             |
 *   |  - Tracks operation lifecycle state         |
 *   |  - Posts events to event bus                |
 *   |  - Maintains termination info in memory     |
 *   +---------------------------------------------+
 *                        |
 *            +-----------+-----------+
 *            |                       |
 *            v                       v
 *   +------------------+    +------------------+
 *   |  GetStatus RPC   |    |  Query History   |
 *   |  (Direct API)    |    |  (Audit Log)     |
 *   +------------------+    +------------------+
 *
 * State Mapping Matrix:
 *
 * ExecuteStatus        -> GetStatus API     -> Query History
 * + TerminationReason
 * ----------------------------------------------------------------
 * Pending              -> RUNNING           -> (no event posted)
 * Started              -> RUNNING           -> STARTED
 * Analyzed             -> RUNNING           -> COMPILED
 * ReadyForExecution    -> RUNNING           -> READY
 * Finished             -> TERMINATING       -> FINISHED
 * Failed               -> TERMINATING       -> FAILED
 * Canceled             -> TERMINATING       -> CANCELED
 * Closed+Succeeded     -> SUCCEEDED         -> CLOSED
 * Closed+Failed        -> FAILED            -> CLOSED
 * Closed+Canceled      -> CANCELLED         -> CLOSED
 * }}}
 *
 * @param executeHolder:
 *   Request for which the events are generated.
 * @param clock:
 *   Source of time for unit tests.
 */
case class ExecuteEventsManager(executeHolder: ExecuteHolder, clock: Clock) {

  private def operationId = executeHolder.operationId

  private def jobTag = executeHolder.jobTag

  private def sparkSessionTags = executeHolder.sparkSessionTags

  private def listenerBus = sessionHolder.session.sparkContext.listenerBus

  private def sessionHolder = executeHolder.sessionHolder

  private def sessionId = executeHolder.request.getSessionId

  private def sessionStatus = sessionHolder.eventManager.status

  @volatile private var _status: ExecuteStatus = ExecuteStatus.Pending

  private var error = Option.empty[Boolean]

  private var canceled = Option.empty[Boolean]

  private var producedRowCount = Option.empty[Long]

  @volatile private var _terminationReason: Option[TerminationReason] = None

  /**
   * @return
   *   Last event posted by the Connect request
   */
  private[connect] def status: ExecuteStatus = _status

  /**
   * @return
   *   The reason for termination, set when the operation finishes, fails, or is canceled. Since
   *   the closed state itself does not convey why the operation ended, this value preserves that
   *   information for later use.
   */
  private[connect] def terminationReason: Option[TerminationReason] = _terminationReason

  /**
   * Updates the termination reason only if the new reason has a higher value than the current
   * one. This established the ordering Canceled > Failed > Succeeded, which is consistent with
   * ExecuteStatus ordering. This handles the cases when execution is interrupted or fails during
   * cleanup.
   */
  private def updateTerminationReason(newReason: TerminationReason): Unit = {
    _terminationReason match {
      case Some(currentReason) if currentReason.value >= newReason.value =>
      case _ =>
        _terminationReason = Some(newReason)
    }
  }

  /**
   * @return
   *   True when the Connect request has posted @link
   *   org.apache.spark.sql.connect.service.SparkListenerConnectOperationCanceled
   */
  private[connect] def hasCanceled: Option[Boolean] = canceled

  /**
   * @return
   *   True when the Connect request has posted @link
   *   org.apache.spark.sql.connect.service.SparkListenerConnectOperationFailed
   */
  private[connect] def hasError: Option[Boolean] = error

  /**
   * @return
   *   How many rows the Connect request has produced @link
   *   org.apache.spark.sql.connect.service.SparkListenerConnectOperationFinished
   */
  private[connect] def getProducedRowCount: Option[Long] = producedRowCount

  /**
   * Post @link org.apache.spark.sql.connect.service.SparkListenerConnectOperationStarted.
   */
  def postStarted(): Unit = {
    assertStatus(List(ExecuteStatus.Pending), ExecuteStatus.Started)
    val request = executeHolder.request
    val plan: Message =
      request.getPlan.getOpTypeCase match {
        case proto.Plan.OpTypeCase.COMMAND => request.getPlan.getCommand
        case proto.Plan.OpTypeCase.ROOT => request.getPlan.getRoot
        case _ => request.getPlan
      }

    val event = SparkListenerConnectOperationStarted(
      jobTag,
      operationId,
      clock.getTimeMillis(),
      sessionId,
      request.getUserContext.getUserId,
      request.getUserContext.getUserName,
      Utils.redact(
        sessionHolder.session.sessionState.conf.stringRedactionPattern,
        ProtoUtils
          .abbreviate(
            plan,
            ExecuteEventsManager.MAX_STATEMENT_TEXT_SIZE,
            ExecuteEventsManager.MAX_STATEMENT_NESTING_LEVEL)
          .toString),
      sparkSessionTags)
    event.planRequest = Some(request)
    listenerBus.post(event)
  }

  /**
   * Post @link org.apache.spark.sql.connect.service.SparkListenerConnectOperationAnalyzed.
   *
   * @param analyzedPlan
   *   The analyzed plan generated by the Connect request plan. None when the request does not
   *   generate a Spark plan or analysis fails.
   * @param parsedPlan
   *   The analyzed plan generated by the Connect request plan. None when the request does not
   *   generate a plan or does not fail analysis.
   */
  def postAnalyzed(
      analyzedPlan: Option[LogicalPlan] = None,
      parsedPlan: Option[LogicalPlan] = None): Unit = {
    assertStatus(List(ExecuteStatus.Started, ExecuteStatus.Analyzed), ExecuteStatus.Analyzed)
    val event =
      SparkListenerConnectOperationAnalyzed(jobTag, operationId, clock.getTimeMillis())
    event.analyzedPlan = analyzedPlan
    event.parsedPlan = parsedPlan
    listenerBus.post(event)
  }

  /**
   * Post @link
   * org.apache.spark.sql.connect.service.SparkListenerConnectOperationReadyForExecution.
   */
  def postReadyForExecution(): Unit = {
    assertStatus(List(ExecuteStatus.Analyzed), ExecuteStatus.ReadyForExecution)
    listenerBus.post(
      SparkListenerConnectOperationReadyForExecution(jobTag, operationId, clock.getTimeMillis()))
  }

  /**
   * Post @link org.apache.spark.sql.connect.service.SparkListenerConnectOperationCanceled.
   */
  def postCanceled(): Unit = {
    // SPARK-53339: Pending is included to handle the case where interrupt() is called before
    // postStarted() transitions the status from Pending to Started.
    assertStatus(
      List(
        ExecuteStatus.Pending,
        ExecuteStatus.Started,
        ExecuteStatus.Analyzed,
        ExecuteStatus.ReadyForExecution,
        ExecuteStatus.Finished,
        ExecuteStatus.Failed),
      ExecuteStatus.Canceled)
    canceled = Some(true)
    updateTerminationReason(TerminationReason.Canceled)
    listenerBus
      .post(SparkListenerConnectOperationCanceled(jobTag, operationId, clock.getTimeMillis()))
  }

  /**
   * Post @link org.apache.spark.sql.connect.service.SparkListenerConnectOperationFailed.
   *
   * @param errorMessage
   *   The message of the error thrown during the request.
   */
  def postFailed(errorMessage: String): Unit = {
    // SPARK-53339: Pending is included to handle the case where postStarted() itself throws
    // an exception (e.g., session state check failure) before transitioning from Pending.
    assertStatus(
      List(
        ExecuteStatus.Pending,
        ExecuteStatus.Started,
        ExecuteStatus.Analyzed,
        ExecuteStatus.ReadyForExecution,
        ExecuteStatus.Finished),
      ExecuteStatus.Failed)
    error = Some(true)
    updateTerminationReason(TerminationReason.Failed)
    listenerBus.post(
      SparkListenerConnectOperationFailed(
        jobTag,
        operationId,
        clock.getTimeMillis(),
        errorMessage))
  }

  /**
   * Post @link org.apache.spark.sql.connect.service.SparkListenerConnectOperationFinished.
   * @param producedRowsCountOpt
   *   Number of rows that are returned to the user. None is expected when the operation does not
   *   return any rows.
   */
  def postFinished(
      producedRowsCountOpt: Option[Long] = None,
      extraTags: Map[String, String] = Map.empty): Unit = {
    assertStatus(
      List(ExecuteStatus.Started, ExecuteStatus.ReadyForExecution),
      ExecuteStatus.Finished)
    producedRowCount = producedRowsCountOpt
    updateTerminationReason(TerminationReason.Succeeded)

    listenerBus
      .post(
        SparkListenerConnectOperationFinished(
          jobTag,
          operationId,
          clock.getTimeMillis(),
          producedRowCount,
          extraTags))
  }

  /**
   * Post @link org.apache.spark.sql.connect.service.SparkListenerConnectOperationClosed.
   */
  def postClosed(): Unit = {
    assertStatus(
      List(ExecuteStatus.Finished, ExecuteStatus.Failed, ExecuteStatus.Canceled),
      ExecuteStatus.Closed)
    listenerBus
      .post(SparkListenerConnectOperationClosed(jobTag, operationId, clock.getTimeMillis()))
  }

  /**
   * @return
   *   \@link A org.apache.spark.sql.catalyst.QueryPlanningTracker that calls postAnalyzed &
   *   postReadyForExecution after analysis & prior execution.
   */
  def createQueryPlanningTracker(): QueryPlanningTracker = {
    new QueryPlanningTracker(Some(new QueryPlanningTrackerCallback {
      def analyzed(tracker: QueryPlanningTracker, analyzedPlan: LogicalPlan): Unit = {
        postAnalyzed(Some(analyzedPlan))
      }

      override def analysisFailed(
          tracker: QueryPlanningTracker,
          parsedPlan: LogicalPlan): Unit = {
        postAnalyzed(parsedPlan = Some(parsedPlan))
      }

      def readyForExecution(tracker: QueryPlanningTracker): Unit = postReadyForExecution()
    }))
  }

  private[connect] def status_(executeStatus: ExecuteStatus): Unit = {
    _status = executeStatus
  }

  private def assertStatus(
      validStatuses: List[ExecuteStatus],
      eventStatus: ExecuteStatus): Unit = {
    if (validStatuses.find(s => s == status).isEmpty) {
      throw IllegalStateErrors.executionStateTransitionInvalidOperationStatus(
        executeHolder.operationId,
        status,
        validStatuses,
        eventStatus)
    }
    val validSessionStatuses = List(SessionStatus.Started, SessionStatus.Closed)
    if (!validSessionStatuses.contains(sessionHolder.eventManager.status)) {
      throw IllegalStateErrors.executionStateTransitionInvalidSessionStatus(
        sessionHolder.sessionId,
        sessionStatus,
        validSessionStatuses,
        eventStatus)
    }
    _status = eventStatus
  }
}

/**
 * Event sent after reception of a Connect request (i.e. not queued), but prior any analysis or
 * execution.
 *
 * @param jobTag:
 *   Opaque Spark jobTag (@link org.apache.spark.SparkContext.setJobGroup) assigned by Connect
 *   during a request. Designed to be unique across sessions and requests.
 * @param operationId:
 *   36 characters UUID assigned by Connect during a request.
 * @param eventTime:
 *   The time in ms when the event was generated.
 * @param sessionId:
 *   ID assigned by the client or Connect the operation was executed on.
 * @param userId:
 *   Opaque userId set in the Connect request.
 * @param userName:
 *   Opaque userName set in the Connect request.
 * @param statementText:
 *   The connect request plan converted to text.
 * @param sparkSessionTags:
 *   Extra tags set by the user (via SparkSession.addTag).
 * @param extraTags:
 *   Additional metadata during the request.
 */
case class SparkListenerConnectOperationStarted(
    jobTag: String,
    operationId: String,
    eventTime: Long,
    sessionId: String,
    userId: String,
    userName: String,
    statementText: String,
    sparkSessionTags: Set[String],
    extraTags: Map[String, String] = Map.empty)
    extends SparkListenerEvent {

  /**
   * The Connect request. None if the operation is not of type @link proto.ExecutePlanRequest
   */
  @JsonIgnore var planRequest: Option[proto.ExecutePlanRequest] = None
}

/**
 * The event is sent after a Connect request has been analyzed (@link
 * org.apache.spark.sql.catalyst.QueryPlanningTracker.ANALYSIS).
 *
 * @param jobTag:
 *   Opaque Spark jobTag (@link org.apache.spark.SparkContext.addJobTag) assigned by Connect
 *   during a request. Designed to be unique across sessions and requests.
 * @param operationId:
 *   36 characters UUID assigned by Connect during a request.
 * @param eventTime:
 *   The time in ms when the event was generated.
 * @param extraTags:
 *   Additional metadata during the request.
 */
case class SparkListenerConnectOperationAnalyzed(
    jobTag: String,
    operationId: String,
    eventTime: Long,
    extraTags: Map[String, String] = Map.empty)
    extends SparkListenerEvent {

  /**
   * Parsed Spark plan generated by the Connect request. None when the Connect request does not
   * generate a Spark plan or does not fail analysis.
   */
  @JsonIgnore var parsedPlan: Option[LogicalPlan] = None

  /**
   * Analyzed Spark plan generated by the Connect request. None when the Connect request does not
   * generate a Spark plan or analysis fails.
   */
  @JsonIgnore var analyzedPlan: Option[LogicalPlan] = None
}

/**
 * The event is sent after a Connect request is ready for execution. For eager commands this is
 * after @link org.apache.spark.sql.catalyst.QueryPlanningTracker.ANALYSIS. For other requests it
 * is after \@link org.apache.spark.sql.catalyst.QueryPlanningTracker.PLANNING
 *
 * @param jobTag:
 *   Opaque Spark jobTag (@link org.apache.spark.SparkContext.addJobTag) assigned by Connect
 *   during a request. Designed to be unique across sessions and requests.
 * @param operationId:
 *   36 characters UUID assigned by Connect during a request.
 * @param eventTime:
 *   The time in ms when the event was generated.
 * @param extraTags:
 *   Additional metadata during the request.
 */
case class SparkListenerConnectOperationReadyForExecution(
    jobTag: String,
    operationId: String,
    eventTime: Long,
    extraTags: Map[String, String] = Map.empty)
    extends SparkListenerEvent

/**
 * Event sent after a Connect request has been canceled.
 *
 * @param jobTag:
 *   Opaque Spark jobTag (@link org.apache.spark.SparkContext.addJobTag) assigned by Connect
 *   during a request. Designed to be unique across sessions and requests.
 * @param operationId:
 *   36 characters UUID assigned by Connect during a request.
 * @param eventTime:
 *   The time in ms when the event was generated.
 * @param extraTags:
 *   Additional metadata during the request.
 */
case class SparkListenerConnectOperationCanceled(
    jobTag: String,
    operationId: String,
    eventTime: Long,
    extraTags: Map[String, String] = Map.empty)
    extends SparkListenerEvent

/**
 * Event sent after a Connect request has failed.
 *
 * @param jobTag:
 *   Opaque Spark jobTag (@link org.apache.spark.SparkContext.addJobTag) assigned by Connect
 *   during a request. Designed to be unique across sessions and requests.
 * @param operationId:
 *   36 characters UUID assigned by Connect during a request.
 * @param eventTime:
 *   The time in ms when the event was generated.
 * @param errorMessage:
 *   The message of the error thrown during the request.
 * @param extraTags:
 *   Additional metadata during the request.
 */
case class SparkListenerConnectOperationFailed(
    jobTag: String,
    operationId: String,
    eventTime: Long,
    errorMessage: String,
    extraTags: Map[String, String] = Map.empty)
    extends SparkListenerEvent

/**
 * Event sent after a Connect request has finished executing, but prior results have been sent to
 * client.
 *
 * @param jobTag:
 *   Opaque Spark jobTag (@link org.apache.spark.SparkContext.addJobTag) assigned by Connect
 *   during a request. Designed to be unique across sessions and requests.
 * @param operationId:
 *   36 characters UUID assigned by Connect during a request.
 * @param eventTime:
 *   The time in ms when the event was generated.
 * @param producedRowCount:
 *   Number of rows that are returned to the user. None is expected when the operation does not
 *   return any rows.
 * @param extraTags:
 *   Additional metadata during the request.
 */
case class SparkListenerConnectOperationFinished(
    jobTag: String,
    operationId: String,
    eventTime: Long,
    producedRowCount: Option[Long] = None,
    extraTags: Map[String, String] = Map.empty)
    extends SparkListenerEvent

/**
 * Event sent after a Connect request has finished executing and results have been sent to client.
 *
 * @param jobTag:
 *   Opaque Spark jobTag (@link org.apache.spark.SparkContext.addJobTag) assigned by Connect
 *   during a request. Designed to be unique across sessions and requests.
 * @param operationId:
 *   36 characters UUID assigned by Connect during a request.
 * @param eventTime:
 *   The time in ms when the event was generated.
 * @param extraTags:
 *   Additional metadata during the request.
 */
case class SparkListenerConnectOperationClosed(
    jobTag: String,
    operationId: String,
    eventTime: Long,
    extraTags: Map[String, String] = Map.empty)
    extends SparkListenerEvent
