from __future__ import annotations

from collections.abc import Iterable
from typing import Any

from market_api.core.config import DatabaseSettings
from market_api.db.sql import (
    build_copy_sql,
    build_create_schema_sql,
    build_create_table_sql,
    build_drop_table_sql,
    record_column_names,
)
from market_api.importer.mappings import SheetSpec


def connect(settings: DatabaseSettings) -> Any:
    import psycopg

    return psycopg.connect(**settings.connect_kwargs())


def replace_table(
    conn: Any,
    schema: str,
    spec: SheetSpec,
    records: Iterable[dict[str, object]],
) -> int:
    columns = record_column_names(spec)
    row_count = 0
    with conn.cursor() as cursor:
        cursor.execute(build_create_schema_sql(schema))
        cursor.execute(build_drop_table_sql(schema, spec))
        cursor.execute(build_create_table_sql(schema, spec))
        with cursor.copy(build_copy_sql(schema, spec)) as copy:
            for record in records:
                copy.write_row([record.get(column) for column in columns])
                row_count += 1
    return row_count

