"""Auto-generated PostgreSQL extraction for {{ contract_id }}.

Generated by Griot scaffold on {{ generated_at }}.
"""
from __future__ import annotations

import os
from typing import Any


def get_connection_string() -> str:
    """Get PostgreSQL connection string from environment."""
    return os.environ.get(
        "POSTGRES_CONNECTION_STRING",
        "postgresql://user:password@localhost:5432/mydb",
    )

{% for schema in schemas %}

def extract_{{ schema.name | to_snake_case }}() -> list[dict[str, Any]]:
    """Extract {{ schema.name }} data from PostgreSQL.

    Uses the contract schema to select only the declared columns:
{%- for field in schema.fields %}
      - {{ field.name }} ({{ field.logical_type }})
{%- endfor %}

    Returns:
        List of row dictionaries.
    """
    import psycopg2
    import psycopg2.extras

    columns = [
{%- for field in schema.fields %}
        "{{ field.name }}",
{%- endfor %}
    ]

    query = f"SELECT {', '.join(columns)} FROM {{ schema.physical_name }}"

    conn = psycopg2.connect(get_connection_string())
    try:
        with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur:
            cur.execute(query)
            return cur.fetchall()
    finally:
        conn.close()
{% endfor %}

if __name__ == "__main__":
{% for schema in schemas %}
    rows_{{ schema.name | to_snake_case }} = extract_{{ schema.name | to_snake_case }}()
    print(f"{{ schema.name }}: extracted { len(rows_{{ schema.name | to_snake_case }}) } rows")
{% endfor %}
