"""The pipeline as a Dagster project.

One asset per load design, partitioned by source tick. Each asset reads the source with a retry policy (up to 3
retries, exponential backoff), applies the row contract, writes its DuckDB table and reports six data checks in the
same step. A sensor adds a tick every 240 seconds and launches the run for live use; a backfill is a run over the
partition keys an outage skipped.

Live:    DAGSTER_HOME=<dir> dagster dev -f dag/definitions.py    (reads the USGS service; tables under PIPELINE_DATA)
Replay:  python3 -B tools/run_study.py ...                        (the same assets, run in-process on recorded ticks)
"""
import os
import sys
import time

import dagster as dg

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(os.path.dirname(HERE), "tools"))
from designs import MAIN, SETTLE_MILLIS, ChangeFeed, connect, table_rows  # noqa: E402
from replay import LiveView, TransientSourceError, planted_failure  # noqa: E402
from score import checks  # noqa: E402
from source import SourceUnavailable, fetch_count  # noqa: E402

TICKS = dg.DynamicPartitionsDefinition(name="ticks")
CHECKS = ("unique_id", "contract", "no_deleted_status", "alias", "count_reconciliation", "freshness")
ERROR_CHECKS = {"unique_id", "contract", "no_deleted_status", "alias"}  # reported at ERROR severity; the load is already committed, nothing is blocked
RETRY_DELAY = float(os.environ.get("PIPELINE_RETRY_DELAY", "5"))
EVERY_S = 240
TRANSIENT = (TransientSourceError, SourceUnavailable, TimeoutError, ConnectionError)  # only the service or the network


class Warehouse:
    """One DuckDB database per design under one folder."""

    def __init__(self, folder):
        self.folder = folder
        os.makedirs(folder, exist_ok=True)

    def connect(self, name):
        return connect(os.path.join(self.folder, f"{name}.duckdb"))


class LiveSource:
    """The live service. Partition keys are the tick's time in epoch milliseconds."""
    planted = False

    def view(self, key):
        return LiveView(int(key), int(key))

    def is_initial(self, key, design):
        return None  # decided by the table: an empty table gets the initial full load

    def interval(self, key):
        t = int(key)
        return t - EVERY_S * 1000 - SETTLE_MILLIS, t - SETTLE_MILLIS

    def count(self, view):
        return fetch_count()

    def fails(self, design, key, attempt):
        return False


def design_asset(design):
    key = f"events_{design.name}"

    @dg.asset(name=key, partitions_def=TICKS, required_resource_keys={"source", "warehouse"},
              retry_policy=dg.RetryPolicy(max_retries=3, delay=RETRY_DELAY, backoff=dg.Backoff.EXPONENTIAL),
              check_specs=[dg.AssetCheckSpec(name=c, asset=key) for c in CHECKS],
              description=f"Earthquake events loaded by the {design.name.replace('_', ' ')} design.")
    def _asset(context: dg.AssetExecutionContext):
        src, wh = context.resources.source, context.resources.warehouse
        pk = context.partition_key
        attempt = context.retry_number + 1
        if src.fails(design.name, pk, attempt):
            raise TransientSourceError(f"planted read failure: {design.name} tick {pk} attempt {attempt}")
        db = None
        try:
            view = src.view(pk)  # live, this reads the service
            db = wh.connect(design.name)
            stats = _load(db, src, view, pk)
        except TRANSIENT:
            raise  # the retry policy retries these: the service or the network may heal
        except Exception as exc:  # anything else is a bug or bad data: fail now, never retry
            raise dg.Failure(description=f"{design.name} tick {pk}: {exc!r}"[:500], allow_retries=False) from exc
        finally:
            if db is not None:
                db.close()
        db = wh.connect(design.name)
        try:
            table = table_rows(db)
        finally:
            db.close()
        res = checks(table, src.count(view), view.now_ms)
        stats.update({"attempt": attempt, "table_rows": len(table)})
        return dg.MaterializeResult(
            metadata=stats,
            check_results=[dg.AssetCheckResult(check_name=c, passed=bool(res[c]),
                                               severity=dg.AssetCheckSeverity.ERROR if c in ERROR_CHECKS
                                               else dg.AssetCheckSeverity.WARN) for c in CHECKS])

    def _load(db, src, view, pk):
        """One transaction: the table moves from one consistent state to the next, or not at all."""
        try:
            db.execute("BEGIN")
            initial = src.is_initial(pk, design.name)
            if initial is None:
                initial = db.execute("SELECT count(*) FROM analytics.events").fetchone()[0] == 0
            if initial:
                stats = design.initial(db, view, view.tick)
            else:
                stats = design.run(db, view, view.tick, partition=src.interval(pk))
            db.execute("COMMIT")
            return stats
        except BaseException:
            db.execute("ROLLBACK")
            raise

    return _asset


DESIGNS = [cls() for cls in MAIN.values()]
SWEEP = [ChangeFeed(lookback_minutes=m, name=f"change_feed_lookback_{m}") for m in (0, 4, 120)]
ASSETS = [design_asset(d) for d in DESIGNS]
SWEEP_ASSETS = [design_asset(d) for d in SWEEP]
live_job = dg.define_asset_job("load_all_designs", selection=[a.key for a in ASSETS], partitions_def=TICKS)


@dg.sensor(job=live_job, minimum_interval_seconds=EVERY_S, default_status=dg.DefaultSensorStatus.RUNNING)
def every_tick(context: dg.SensorEvaluationContext):
    key = str(int(time.time() * 1000))
    return dg.SensorResult(run_requests=[dg.RunRequest(partition_key=key, run_key=key)],
                           dynamic_partitions_requests=[TICKS.build_add_request([key])])


defs = dg.Definitions(
    assets=ASSETS, jobs=[live_job], sensors=[every_tick],
    resources={"source": LiveSource(),
               "warehouse": Warehouse(os.environ.get("PIPELINE_DATA", os.path.expanduser("~/.cache/pipelines-that-break/live")))})
