"""Side-by-side timing helper: external table (query Iceberg directly)
vs materialised view (CTAS into the warehouse engine).

Both tracks run this script. On Track A (Snowflake / BigQuery) the
materialised path is a SQL-level CREATE TABLE AS SELECT; on Track B
(DuckDB local) it's the same CTAS but inside DuckDB's persistent file.
The numbers shape the L11 'when to materialize vs query directly'
discussion.
"""

from __future__ import annotations

import time

from iceberg.query_duckdb import open_with_iceberg
from warehouse.duckdb_local import LOCAL_DUCKDB_PATH


def bench_external() -> float:
    con = open_with_iceberg()
    t0 = time.perf_counter()
    con.execute("""
        SELECT event_date, type, count(*)
        FROM events
        WHERE event_date >= current_date - INTERVAL 7 DAY
        GROUP BY event_date, type
    """).fetchall()
    return time.perf_counter() - t0


def bench_materialized() -> float:
    import duckdb
    con = duckdb.connect(LOCAL_DUCKDB_PATH)
    t0 = time.perf_counter()
    con.execute("""
        SELECT event_date, type, n
        FROM daily_counts
        WHERE event_date >= current_date - INTERVAL 7 DAY
    """).fetchall()
    return time.perf_counter() - t0


def main() -> None:
    ext = bench_external()
    mat = bench_materialized()
    print(f"external (iceberg scan): {ext:.3f}s")
    print(f"materialized (CTAS):     {mat:.3f}s")
    print(f"speedup: {ext / mat:.1f}x")


if __name__ == "__main__":
    main()
