"""Lakehouse pipeline for the TLC yellow trip records, run as Databricks job tasks.

Stages (first argument):
  naive    read every raw file with the newest (2025) schema, the way a pipeline written for today's
           files would, and record per file what loads: rows, rows with a usable pickup time, and the
           non-null count of every column. A file the read refuses is recorded with its error class.
  merge    read the raw folder with schema merging switched on, record what comes back or the error.
  silver   schema-aware load: map each era's column names and types to one canonical schema, keep
           the source file and month on every row, flag defects; write a Delta table.
  gold     dimensional model on top of silver: fact_trip plus date, zone, vendor, payment and rate
           dimensions, all Delta.
  layouts  three copies of fact_trip that differ only in physical layout: none, partitioned by
           source month (the month of the file a row came from), liquid clustered by pickup date and pickup zone.
  shuffled the same rows in random order (first follow-up).
  alternatives  two loads without an era map (third follow-up): Delta schema evolution on append, and every
           number read as the widest numeric then cast back. See stage_alternatives.
  wide_by_kind  third follow-up, variant b2: integers read as bigint, decimals as double, then cast back.

Every stage writes its measurements to a small Delta table in the same schema, so the command line
can read them back through the SQL warehouse.
"""
import sys
from pyspark.sql import SparkSession, functions as F

CAT, SCH = "workspace", "lakehouse_trips"
RAW = f"/Volumes/{CAT}/{SCH}/raw/yellow"
ZONES = f"/Volumes/{CAT}/{SCH}/raw/reference/taxi_zone_lookup.csv"
Q = f"{CAT}.{SCH}"

spark = SparkSession.builder.getOrCreate()


def raw_files():
    rows = spark.sql(f"LIST '{RAW}'").collect()
    return sorted(r.path for r in rows if r.path.endswith(".parquet"))


def month_of(path):
    return path.rsplit("_", 1)[-1].replace(".parquet", "")


def stage_naive():
    out = []
    files = raw_files()
    # The schema exactly as Spark reads the newest file; every file is then read with it, by name.
    newest = spark.read.parquet(files[-1]).schema
    for p in files:
        m = month_of(p)
        try:
            df = spark.read.schema(newest).parquet(p)
            aggs = [F.count(F.lit(1)).alias("rows")] + [F.count(F.col(c)).alias(c) for c in newest.fieldNames()]
            r = df.agg(*aggs).collect()[0].asDict()
            for c in newest.fieldNames():
                out.append((m, "ok", "", int(r["rows"]), c, int(r[c])))
        except Exception as e:  # recorded, never swallowed: the error class is the result
            msg = (type(e).__name__ + ": " + str(e)).replace("\n", " ")[:400]
            out.append((m, "error", msg, None, None, None))
    sch = "month string, status string, error string, rows long, column_name string, non_null long"
    spark.createDataFrame(out, sch).write.mode("overwrite").saveAsTable(f"{Q}.m_naive_load")


def stage_merge():
    try:
        df = spark.read.option("mergeSchema", "true").parquet(RAW)
        cols = df.columns
        n = df.count()
        rec = [("ok", "", n, len(cols), ",".join(cols))]
    except Exception as e:
        rec = [("error", (type(e).__name__ + ": " + str(e)).replace("\n", " ")[:600], None, None, None)]
    spark.createDataFrame(rec, "status string, error string, rows long, n_columns int, columns string") \
        .write.mode("overwrite").saveAsTable(f"{Q}.m_merge_load")


# canonical name -> source expression, per schema era. Eras come from the footer census.
def era_of(month):
    y = int(month[:4])
    return "2009" if y == 2009 else "2010" if y == 2010 else "2011+"


def tc(col, typ):
    """try_cast: serverless runs SQL in ANSI mode, where a plain cast of a bad value raises instead of nulling."""
    return F.expr(f"try_cast(`{col}` AS {typ})")


NULL = {t: F.lit(None).cast(t) for t in ("int", "double", "string")}


def canon_old(src):
    """2009 and 2010: text times, coordinates instead of zones, text payment codes. src maps role -> column."""
    return {
        "vendor": F.upper(F.trim(F.col(src["vendor"]))),
        "pickup_ts": tc(src["pickup"], "timestamp_ntz"),
        "dropoff_ts": tc(src["dropoff"], "timestamp_ntz"),
        "passenger_count": tc(src["passengers"], "int"),
        "trip_distance": tc(src["distance"], "double"),
        "rate_code_id": tc(src["rate"], "int"),
        "pu_location_id": NULL["int"], "do_location_id": NULL["int"],
        "pickup_lon": tc(src["lon"], "double"), "pickup_lat": tc(src["lat"], "double"),
        "payment_raw": F.upper(F.trim(F.col(src["payment"]))),
        "fare_amount": tc(src["fare"], "double"), "extra": tc("surcharge", "double"),
        "mta_tax": tc("mta_tax", "double"), "tip_amount": tc(src["tip"], "double"),
        "tolls_amount": tc(src["tolls"], "double"), "improvement_surcharge": NULL["double"],
        "total_amount": tc(src["total"], "double"), "congestion_surcharge": NULL["double"],
        "airport_fee": NULL["double"], "cbd_congestion_fee": NULL["double"],
    }


CANON = {
    "2009": canon_old({"vendor": "vendor_name", "pickup": "Trip_Pickup_DateTime", "dropoff": "Trip_Dropoff_DateTime",
                       "passengers": "Passenger_Count", "distance": "Trip_Distance", "rate": "Rate_Code",
                       "lon": "Start_Lon", "lat": "Start_Lat", "payment": "Payment_Type", "fare": "Fare_Amt",
                       "tip": "Tip_Amt", "tolls": "Tolls_Amt", "total": "Total_Amt"}),
    "2010": canon_old({"vendor": "vendor_id", "pickup": "pickup_datetime", "dropoff": "dropoff_datetime",
                       "passengers": "passenger_count", "distance": "trip_distance", "rate": "rate_code",
                       "lon": "pickup_longitude", "lat": "pickup_latitude", "payment": "payment_type",
                       "fare": "fare_amount", "tip": "tip_amount", "tolls": "tolls_amount", "total": "total_amount"}),
}


def canon_2011(cols):
    """2011 on: one layout, but names differ in case and types drift (int64 vs int32, double vs int64)."""
    lower = {c.lower(): c for c in cols}
    def c(name, typ="double"):
        return tc(lower[name], typ) if name in lower else NULL.get(typ, F.lit(None).cast(typ))
    vid = c("vendorid", "int")
    return {
        "vendor": F.when(vid == 1, "CMT").when(vid == 2, "VTS").otherwise(vid.cast("string")),
        "pickup_ts": c("tpep_pickup_datetime", "timestamp_ntz"),
        "dropoff_ts": c("tpep_dropoff_datetime", "timestamp_ntz"),
        "passenger_count": c("passenger_count", "int"),
        "trip_distance": c("trip_distance"),
        "rate_code_id": c("ratecodeid", "int"),
        "pu_location_id": c("pulocationid", "int"), "do_location_id": c("dolocationid", "int"),
        "pickup_lon": NULL["double"], "pickup_lat": NULL["double"],
        "payment_raw": c("payment_type", "string"),
        "fare_amount": c("fare_amount"), "extra": c("extra"), "mta_tax": c("mta_tax"),
        "tip_amount": c("tip_amount"), "tolls_amount": c("tolls_amount"),
        "improvement_surcharge": c("improvement_surcharge"), "total_amount": c("total_amount"),
        "congestion_surcharge": c("congestion_surcharge"), "airport_fee": c("airport_fee"),
        "cbd_congestion_fee": c("cbd_congestion_fee"),
    }


# One payment code set across eras (2011+ numeric codes as the TLC dictionary defines them).
PAYMENT = F.expr("""CASE
  WHEN payment_raw IN ('1','CREDIT','CRE','CRD') THEN 1
  WHEN payment_raw IN ('2','CASH','CAS','CSH') THEN 2
  WHEN payment_raw IN ('3','NO CHARGE','NOC','NO') THEN 3
  WHEN payment_raw IN ('4','DISPUTE','DIS') THEN 4
  WHEN payment_raw IN ('5','UNK') THEN 5
  WHEN payment_raw IN ('6') THEN 6
  WHEN payment_raw IN ('0') THEN 0
  ELSE NULL END""")


def stage_silver(months=None, table="silver_trips"):
    parts = []
    for p in raw_files():
        m = month_of(p)
        if months and m not in months:
            continue
        df = spark.read.parquet(p)
        mp = CANON[era_of(m)] if era_of(m) in CANON else canon_2011(df.columns)
        sel = [expr.alias(name) for name, expr in mp.items()]
        parts.append(df.select(*sel, F.lit(m).alias("source_month"), F.lit(p.rsplit("/", 1)[-1]).alias("source_file")))
    u = parts[0]
    for d in parts[1:]:
        u = u.unionByName(d)
    u = u.withColumn("payment_type", PAYMENT)
    pm = F.to_date(F.concat(F.col("source_month"), F.lit("-01")))
    u = (u.withColumn("pickup_date", F.to_date("pickup_ts"))
          .withColumn("flag_no_pickup_time", F.col("pickup_ts").isNull())
          .withColumn("flag_outside_file_month", F.trunc("pickup_ts", "month") != pm)
          .withColumn("flag_dropoff_before_pickup", F.col("dropoff_ts") < F.col("pickup_ts"))
          .withColumn("flag_nonpositive_distance", F.col("trip_distance") <= 0)
          .withColumn("flag_negative_total", F.col("total_amount") < 0)
          .withColumn("flag_no_passenger_count", F.coalesce(F.col("passenger_count"), F.lit(0)) == 0)
          .withColumn("flag_unknown_zone", F.col("pu_location_id").isin(264, 265) |
                      (F.col("pu_location_id").isNull() & ((F.col("pickup_lat") == 0) | F.col("pickup_lat").isNull()))))
    u.write.mode("overwrite").option("overwriteSchema", "true").saveAsTable(f"{Q}.{table}")


def stage_gold():
    spark.sql(f"""CREATE OR REPLACE TABLE {Q}.dim_zone AS
      SELECT CAST(LocationID AS INT) zone_id, Borough borough, Zone zone, service_zone
      FROM read_files('{ZONES}', format => 'csv', header => true)""")
    spark.sql(f"""CREATE OR REPLACE TABLE {Q}.dim_payment_type AS SELECT * FROM VALUES
      (0,'Flex fare'),(1,'Credit card'),(2,'Cash'),(3,'No charge'),(4,'Dispute'),(5,'Unknown'),(6,'Voided trip')
      AS t(payment_type, payment_name)""")
    spark.sql(f"""CREATE OR REPLACE TABLE {Q}.dim_rate_code AS SELECT * FROM VALUES
      (1,'Standard'),(2,'JFK'),(3,'Newark'),(4,'Nassau or Westchester'),(5,'Negotiated'),(6,'Group ride'),(99,'Unknown')
      AS t(rate_code_id, rate_name)""")
    spark.sql(f"""CREATE OR REPLACE TABLE {Q}.dim_vendor AS
      SELECT vendor, count(*) trips FROM {Q}.silver_trips GROUP BY vendor""")
    spark.sql(f"""CREATE OR REPLACE TABLE {Q}.dim_date AS
      SELECT d AS date_key, year(d) year, month(d) month, dayofweek(d) day_of_week,
             date_format(d, 'yyyy-MM') year_month
      FROM (SELECT explode(sequence(DATE'2008-12-01', DATE'2025-02-28', INTERVAL 1 DAY)) d)""")
    spark.sql(f"""CREATE OR REPLACE TABLE {Q}.fact_trip AS
      SELECT source_month, pickup_date, date_format(pickup_date,'yyyy-MM') pickup_month, pickup_ts, dropoff_ts,
             vendor, pu_location_id, do_location_id, payment_type, rate_code_id, passenger_count,
             trip_distance, fare_amount, tip_amount, tolls_amount, total_amount, congestion_surcharge, airport_fee,
             NOT (flag_no_pickup_time OR flag_outside_file_month OR flag_dropoff_before_pickup
                  OR flag_nonpositive_distance OR flag_negative_total) AS is_valid
      FROM {Q}.silver_trips""")


def stage_layouts():
    src = f"{Q}.fact_trip"
    spark.sql(f"CREATE OR REPLACE TABLE {Q}.fact_plain AS SELECT * FROM {src}")
    spark.sql(f"CREATE OR REPLACE TABLE {Q}.fact_by_month PARTITIONED BY (source_month) AS SELECT * FROM {src}")
    spark.sql(f"CREATE OR REPLACE TABLE {Q}.fact_clustered CLUSTER BY (pickup_date, pu_location_id) AS SELECT * FROM {src}")
    spark.sql(f"OPTIMIZE {Q}.fact_clustered")


def stage_shuffled():
    """Follow-up: the same rows in random order, no layout, to test whether plain-table skipping is load order."""
    spark.sql(f"CREATE OR REPLACE TABLE {Q}.fact_shuffled AS SELECT * FROM {Q}.fact_trip ORDER BY rand(17)")


def _err(e, n=500):
    return (type(e).__name__ + ": " + str(e)).replace("\n", " ")[:n]


def stage_alternatives():
    """Third follow-up: two simpler ways to load the history without an era map, against the map.

    evolve  the platform's schema evolution: a Delta table made from the newest (2025) file, then each older file
            appended newest to oldest with mergeSchema on (new and renamed columns are added automatically) and
            type widening switched on where the table accepts it. Records each append's outcome, then per source
            month the rows and the non-null count of every column, and the final columns and types.
    wide    every file read with the newest file's names but every number read as the widest numeric (double),
            then cast back to the newest file's types. Records per file the outcome and, per column, non-null
            values as read and after the cast.
    """
    files = raw_files()
    newest_path = files[-1]
    newest = spark.read.parquet(newest_path).schema

    # (a) schema evolution on append
    T = f"{Q}.alt_evolve"
    log = []
    spark.sql(f"DROP TABLE IF EXISTS {T}")
    spark.read.parquet(newest_path).withColumn("source_month", F.lit(month_of(newest_path))).write.saveAsTable(T)
    try:
        spark.sql(f"ALTER TABLE {T} SET TBLPROPERTIES ('delta.enableTypeWidening' = 'true')")
        log.append(("table", "type_widening", "ok", ""))
    except Exception as e:
        log.append(("table", "type_widening", "error", _err(e)))
    for p in reversed(files[:-1]):
        m = month_of(p)
        try:
            (spark.read.parquet(p).withColumn("source_month", F.lit(m))
             .write.mode("append").option("mergeSchema", "true").saveAsTable(T))
            log.append((m, "append", "ok", ""))
        except Exception as e:  # the refusal is the result
            log.append((m, "append", "error", _err(e)))
    spark.createDataFrame(log, "month string, step string, status string, error string") \
        .write.mode("overwrite").saveAsTable(f"{Q}.m_alt_evolve_log")
    t = spark.table(T)
    cols = [c for c in t.columns if c != "source_month"]
    spark.createDataFrame([(f.name, f.dataType.simpleString()) for f in t.schema.fields], "column_name string, type string") \
        .write.mode("overwrite").saveAsTable(f"{Q}.m_alt_evolve_columns")
    aggs = [F.count(F.lit(1)).alias("rows")] + [F.count(F.col(f"`{c}`")).alias(f"nn{i}") for i, c in enumerate(cols)]
    rows = []
    for r in t.groupBy("source_month").agg(*aggs).collect():
        for i, c in enumerate(cols):
            rows.append((r["source_month"], int(r["rows"]), c, int(r[f"nn{i}"])))
    spark.createDataFrame(rows, "month string, rows long, column_name string, non_null long") \
        .write.mode("overwrite").saveAsTable(f"{Q}.m_alt_evolve")

    # (b) wide types, cast afterwards
    from pyspark.sql.types import StructType, StructField, DoubleType, IntegerType, LongType, FloatType, ShortType
    num = (IntegerType, LongType, FloatType, ShortType, DoubleType)
    wide = StructType([StructField(f.name, DoubleType() if isinstance(f.dataType, num) else f.dataType, True)
                       for f in newest.fields])
    out = []
    for p in files:
        m = month_of(p)
        try:
            df = spark.read.schema(wide).parquet(p)
            cast = [F.expr(f"try_cast(`{f.name}` AS {f.dataType.simpleString()})").alias(f.name) for f in newest.fields]
            d2 = df.select(*[F.col(f"`{f.name}`").alias("w_" + f.name) for f in newest.fields], *cast)
            aggs = [F.count(F.lit(1)).alias("rows")] + \
                   [F.count(F.col(f"`w_{f.name}`")).alias(f"w{i}") for i, f in enumerate(newest.fields)] + \
                   [F.count(F.col(f"`{f.name}`")).alias(f"c{i}") for i, f in enumerate(newest.fields)]
            r = d2.agg(*aggs).collect()[0]
            for i, f in enumerate(newest.fields):
                out.append((m, "ok", "", int(r["rows"]), f.name, int(r[f"w{i}"]), int(r[f"c{i}"])))
        except Exception as e:
            out.append((m, "error", _err(e), None, None, None, None))
    spark.createDataFrame(out, "month string, status string, error string, rows long, column_name string, "
                               "non_null_read long, non_null_cast long") \
        .write.mode("overwrite").saveAsTable(f"{Q}.m_alt_wide")



def stage_wide_by_kind():
    """Third follow-up, variant b2 (declared in FOLLOWUP-r3b.md after b was refused on every file): every integer
    column read as bigint (the widest integer) and every decimal column as double, by the 2025 file's types, then
    cast back to the 2025 types with a safe cast. Same records as the wide variant, table m_alt_wide_by_kind."""
    from pyspark.sql.types import StructType, StructField, DoubleType, IntegerType, LongType, FloatType, ShortType
    files = raw_files()
    newest = spark.read.parquet(files[-1]).schema
    def widen(t):
        if isinstance(t, (IntegerType, LongType, ShortType)):
            return LongType()
        if isinstance(t, (FloatType, DoubleType)):
            return DoubleType()
        return t
    wide = StructType([StructField(f.name, widen(f.dataType), True) for f in newest.fields])
    out = []
    for p in files:
        m = month_of(p)
        try:
            df = spark.read.schema(wide).parquet(p)
            cast = [F.expr(f"try_cast(`{f.name}` AS {f.dataType.simpleString()})").alias(f.name) for f in newest.fields]
            d2 = df.select(*[F.col(f"`{f.name}`").alias("w_" + f.name) for f in newest.fields], *cast)
            aggs = [F.count(F.lit(1)).alias("rows")] + \
                   [F.count(F.col(f"`w_{f.name}`")).alias(f"w{i}") for i, f in enumerate(newest.fields)] + \
                   [F.count(F.col(f"`{f.name}`")).alias(f"c{i}") for i, f in enumerate(newest.fields)]
            r = d2.agg(*aggs).collect()[0]
            for i, f in enumerate(newest.fields):
                out.append((m, "ok", "", int(r["rows"]), f.name, int(r[f"w{i}"]), int(r[f"c{i}"])))
        except Exception as e:
            out.append((m, "error", _err(e), None, None, None, None))
    spark.createDataFrame(out, "month string, status string, error string, rows long, column_name string, "
                               "non_null_read long, non_null_cast long") \
        .write.mode("overwrite").saveAsTable(f"{Q}.m_alt_wide_by_kind")


CANON_COLS = ["vendor", "pickup_ts", "dropoff_ts", "passenger_count", "trip_distance", "rate_code_id",
              "pu_location_id", "do_location_id", "pickup_lon", "pickup_lat", "payment_raw", "payment_type",
              "fare_amount", "extra", "mta_tax", "tip_amount", "tolls_amount", "improvement_surcharge",
              "total_amount", "congestion_surcharge", "airport_fee", "cbd_congestion_fee"]
FLAGS = ["flag_no_pickup_time", "flag_outside_file_month", "flag_dropoff_before_pickup", "flag_nonpositive_distance",
         "flag_negative_total", "flag_no_passenger_count", "flag_unknown_zone"]


def stage_checks(table="silver_trips"):
    """Per source month: rows, non-null count of every canonical column, every defect flag, and the payment
    codes that mapped to no known code (with their counts)."""
    t = spark.table(f"{Q}.{table}")
    aggs = [F.count(F.lit(1)).alias("rows")] + [F.count(F.col(c)).alias("nn_" + c) for c in CANON_COLS] + \
           [F.sum(F.col(f).cast("long")).alias(f) for f in FLAGS]
    t.groupBy("source_month").agg(*aggs).write.mode("overwrite").option("overwriteSchema", "true") \
        .saveAsTable(f"{Q}.m_silver_checks_{table}")
    (t.where(F.col("payment_type").isNull()).groupBy("source_month", "payment_raw").count()
      .write.mode("overwrite").option("overwriteSchema", "true").saveAsTable(f"{Q}.m_unmapped_payment_{table}"))


if __name__ == "__main__":
    if sys.argv[1] == "silver" and len(sys.argv) > 2:
        stage_silver(months=sys.argv[2].split(","), table=sys.argv[3])
    elif sys.argv[1] == "checks" and len(sys.argv) > 2:
        stage_checks(table=sys.argv[2])
    else:
        {"naive": stage_naive, "merge": stage_merge, "silver": stage_silver, "checks": stage_checks,
         "gold": stage_gold, "layouts": stage_layouts, "shuffled": stage_shuffled,
         "alternatives": stage_alternatives, "wide_by_kind": stage_wide_by_kind}[sys.argv[1]]()
