"""Read the Iceberg ``default.events`` table from DuckDB.

Uses DuckDB's iceberg extension to read the metadata + manifest files
directly.  No data copy, no materialisation step.

The Iceberg table's logical schema uses column ``actor`` and partition
column ``event_date`` (the ingestion step in write_from_parquet.py
renames the source ``date`` column to ``event_date``).
"""

from __future__ import annotations

import duckdb

from .tables import create_or_load_events


def open_with_iceberg() -> duckdb.DuckDBPyConnection:
    """Return a DuckDB connection with an ``events`` view over the Iceberg table.

    The view is built via DuckDB's iceberg extension using the current
    metadata_location from the pyiceberg catalog.  Reopen the connection
    after a schema change so the extension picks up the updated metadata.
    """
    table = create_or_load_events()
    metadata_location = table.metadata_location

    con = duckdb.connect(":memory:")
    con.execute("INSTALL iceberg")
    con.execute("LOAD iceberg")
    con.execute(
        f"""
        CREATE OR REPLACE VIEW events AS
        SELECT * FROM iceberg_scan('{metadata_location}');
        """
    )
    return con


if __name__ == "__main__":
    with open_with_iceberg() as con:
        row = con.execute("SELECT count(*) FROM events").fetchone()
        print(f"iceberg events row count = {row[0]}")
