# 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.

"""
TPC-H Problem Statement Query 9:

The Product Type Profit Measure Query finds, for each nation and each year, the profit for all parts
ordered in that year that contain a specified substring in their names and that were filled by a
supplier in that nation. The profit is defined as the sum of
[(l_extendedprice*(1-l_discount)) - (ps_supplycost * l_quantity)] for all lineitems describing
parts in the specified line. The query lists the nations in ascending alphabetical order and, for
each nation, the year and profit in descending order by year (most recent first).

The above problem statement text is copyrighted by the Transaction Processing Performance Council
as part of their TPC Benchmark H Specification revision 2.18.0.

Reference SQL (from TPC-H specification, used by the benchmark suite)::

    select
        nation,
        o_year,
        sum(amount) as sum_profit
    from
        (
                select
                        n_name as nation,
                        extract(year from o_orderdate) as o_year,
                        l_extendedprice * (1 - l_discount) - ps_supplycost * l_quantity as amount
                from
                        part,
                        supplier,
                        lineitem,
                        partsupp,
                        orders,
                        nation
                where
                        s_suppkey = l_suppkey
                        and ps_suppkey = l_suppkey
                        and ps_partkey = l_partkey
                        and p_partkey = l_partkey
                        and o_orderkey = l_orderkey
                        and s_nationkey = n_nationkey
                        and p_name like '%green%'
        ) as profit
    group by
        nation,
        o_year
    order by
        nation,
        o_year desc;
"""

import pyarrow as pa
from datafusion import SessionContext, col, lit
from datafusion import functions as F
from util import get_data_path

part_color = "green"

# Load the dataframes we need

ctx = SessionContext()

df_part = ctx.read_parquet(get_data_path("part.parquet")).select("p_partkey", "p_name")
df_supplier = ctx.read_parquet(get_data_path("supplier.parquet")).select(
    "s_suppkey", "s_nationkey"
)
df_partsupp = ctx.read_parquet(get_data_path("partsupp.parquet")).select(
    "ps_suppkey", "ps_partkey", "ps_supplycost"
)
df_lineitem = ctx.read_parquet(get_data_path("lineitem.parquet")).select(
    "l_partkey",
    "l_extendedprice",
    "l_discount",
    "l_suppkey",
    "l_orderkey",
    "l_quantity",
)
df_orders = ctx.read_parquet(get_data_path("orders.parquet")).select(
    "o_orderkey", "o_custkey", "o_orderdate"
)
df_nation = ctx.read_parquet(get_data_path("nation.parquet")).select(
    "n_nationkey", "n_name", "n_regionkey"
)

# Limit possible parts to the color specified, then walk the joins down to the
# line-item rows we need and attach the supplier's nation. ``F.contains``
# maps directly to the reference SQL's ``p_name like '%green%'``.
df = (
    df_part.filter(F.contains(col("p_name"), lit(part_color)))
    .join(df_lineitem, left_on="p_partkey", right_on="l_partkey")
    .join(df_supplier, left_on="l_suppkey", right_on="s_suppkey")
    .join(df_orders, left_on="l_orderkey", right_on="o_orderkey")
    .join(
        df_partsupp,
        left_on=["l_suppkey", "l_partkey"],
        right_on=["ps_suppkey", "ps_partkey"],
    )
    .join(df_nation, left_on="s_nationkey", right_on="n_nationkey")
)

# Compute the intermediate values and limit down to the expressions we need
df = df.select(
    col("n_name").alias("nation"),
    F.datepart(lit("year"), col("o_orderdate")).cast(pa.int32()).alias("o_year"),
    (
        col("l_extendedprice") * (lit(1) - col("l_discount"))
        - col("ps_supplycost") * col("l_quantity")
    ).alias("amount"),
)

# Sum up the values by nation and year, then sort per the spec.
df = df.aggregate(["nation", "o_year"], [F.sum(col("amount")).alias("profit")]).sort(
    "nation", col("o_year").sort(ascending=False)
)

df.show()
