/*
 * 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.texera.amber.operator.visualization.sankeyDiagram

import com.fasterxml.jackson.annotation.{JsonProperty, JsonPropertyDescription}
import com.kjetland.jackson.jsonSchema.annotations.JsonSchemaTitle
import org.apache.texera.amber.core.tuple.{AttributeType, Schema}
import org.apache.texera.amber.pybuilder.PythonTemplateBuilder.PythonTemplateBuilderStringContext
import org.apache.texera.amber.pybuilder.PyStringTypes.EncodableString
import org.apache.texera.amber.core.workflow.PortIdentity
import org.apache.texera.amber.operator.PythonOperatorDescriptor
import org.apache.texera.amber.operator.metadata.annotations.AutofillAttributeName
import org.apache.texera.amber.operator.metadata.{OperatorGroupConstants, OperatorInfo}
import org.apache.texera.amber.pybuilder.PythonTemplateBuilder

import javax.validation.constraints.NotNull

class SankeyDiagramOpDesc extends PythonOperatorDescriptor {

  @JsonProperty(value = "Source Attribute", required = true)
  @JsonSchemaTitle("Source Attribute")
  @JsonPropertyDescription("The source node of the Sankey diagram")
  @AutofillAttributeName
  @NotNull(message = "Source Attribute cannot be empty")
  var sourceAttribute: EncodableString = ""

  @JsonProperty(value = "Target Attribute", required = true)
  @JsonSchemaTitle("Target Attribute")
  @JsonPropertyDescription("The target node of the Sankey diagram")
  @AutofillAttributeName
  @NotNull(message = "Target Attribute cannot be empty")
  var targetAttribute: EncodableString = ""

  @JsonProperty(value = "Value Attribute", required = true)
  @JsonSchemaTitle("Value Attribute")
  @JsonPropertyDescription("The value/volume of the flow between source and target")
  @AutofillAttributeName
  @NotNull(message = "Value Attribute cannot be empty")
  var valueAttribute: EncodableString = ""

  override def getOutputSchemas(
      inputSchemas: Map[PortIdentity, Schema]
  ): Map[PortIdentity, Schema] = {
    val outputSchema = Schema()
      .add("html-content", AttributeType.STRING)
    Map(operatorInfo.outputPorts.head.id -> outputSchema)
    Map(operatorInfo.outputPorts.head.id -> outputSchema)
  }

  override def operatorInfo: OperatorInfo =
    OperatorInfo.forVisualization(
      "Sankey Diagram",
      "Visualize data using a Sankey diagram",
      OperatorGroupConstants.VISUALIZATION_BASIC_GROUP
    )

  def createPlotlyFigure(): PythonTemplateBuilder = {
    pyb"""
         |        # Grouping source, target, and summing value for the Sankey diagram
         |        table = table.groupby([$sourceAttribute, $targetAttribute])[$valueAttribute].sum().reset_index(name='value')
         |
         |        # Create a list of unique labels from both source and target
         |        labels = pd.concat([table[$sourceAttribute], table[$targetAttribute]]).unique().tolist()
         |
         |        # Create indices for source and target from the label list
         |        table['source_index'] = table[$sourceAttribute].apply(lambda x: labels.index(x))
         |        table['target_index'] = table[$targetAttribute].apply(lambda x: labels.index(x))
         |
         |        # Create the Sankey diagram
         |        fig = go.Figure(data=[go.Sankey(
         |            node=dict(
         |                pad=15,
         |                thickness=20,
         |                line=dict(color="black", width=0.5),
         |                label=labels,
         |                color="blue"
         |            ),
         |            link=dict(
         |                source=table['source_index'].tolist(),
         |                target=table['target_index'].tolist(),
         |                value=table['value'].tolist()
         |            )
         |        )])
         |
         |        fig.update_layout(title_text="Sankey Diagram", font_size=10)
         |"""
  }

  override def generatePythonCode(): String = {
    val finalCode =
      pyb"""
         |from pytexera import *
         |import plotly.graph_objects as go
         |import plotly.io
         |import pandas as pd
         |
         |class ProcessTableOperator(UDFTableOperator):
         |
         |    def render_error(self, error_msg):
         |        return '''<h1>Sankey Diagram is not available.</h1>
         |                  <p>Reasons are: {} </p>
         |               '''.format(error_msg)
         |
         |    @overrides
         |    def process_table(self, table: Table, port: int) -> Iterator[Optional[TableLike]]:
         |        if table.empty:
         |            yield {'html-content': self.render_error("Input table is empty.")}
         |            return
         |        ${createPlotlyFigure()}
         |        if table.empty:
         |            yield {'html-content': self.render_error("No valid rows left (every row has at least 1 missing value).")}
         |            return
         |        # convert fig to html content
         |        html = plotly.io.to_html(fig, include_plotlyjs='cdn', auto_play=False)
         |        yield {'html-content': html}
         |"""
    finalCode.encode
  }
}
