"""Helper functions that reshape parsed DBML data for Jinja2 template consumption.

Keeps logic out of templates (generator-coding Rule 3).
"""

# ---------------------------------------------------------------------------
# Type mapping
# ---------------------------------------------------------------------------

DBML_TO_SQLITE = {
    "int": "INTEGER",
    "integer": "INTEGER",
    "varchar": "TEXT",
    "text": "TEXT",
    "date": "TEXT",
    "datetime": "TEXT",
    "boolean": "INTEGER",
    "float": "REAL",
    "real": "REAL",
}


def dbml_type_to_sqlite(dbml_type: str) -> str:
    """Map a DBML column type to its SQLite equivalent."""
    return DBML_TO_SQLITE.get(dbml_type.lower(), "TEXT")


# ---------------------------------------------------------------------------
# Table context builder
# ---------------------------------------------------------------------------


def build_table_context(table: dict, refs: list[dict]) -> dict:
    """Attach FK info to columns and produce a template-ready table dict.

    Parameters
    ----------
    table : dict
        Parsed table with keys: name, columns (list of column dicts).
    refs : list[dict]
        All parsed Ref entries with keys: from_table, from_column, to_table, to_column.

    Returns
    -------
    dict with keys: name, columns (enriched with sqlite_type, fk_table, fk_column).
    """
    # Index refs by (from_table, from_column) for O(1) lookup.
    ref_index: dict[tuple[str, str], dict] = {
        (r["from_table"], r["from_column"]): r for r in refs
    }

    enriched_columns = []
    for col in table["columns"]:
        sqlite_type = dbml_type_to_sqlite(col["type"])
        fk = ref_index.get((table["name"], col["name"]))
        enriched_columns.append(
            {
                "name": col["name"],
                "sqlite_type": sqlite_type,
                "is_pk": col.get("is_pk", False),
                "is_autoincrement": col.get("is_autoincrement", False),
                "is_not_null": col.get("is_not_null", False),
                "is_nullable": col.get("is_nullable", False),
                "fk_table": fk["to_table"] if fk else None,
                "fk_column": fk["to_column"] if fk else None,
            }
        )

    return {"name": table["name"], "columns": enriched_columns}


# ---------------------------------------------------------------------------
# Seed data context builder
# ---------------------------------------------------------------------------


def build_seed_context(seed_blocks: list[dict]) -> list[dict]:
    """Convert parsed seed blocks into template-ready insert contexts.

    Parameters
    ----------
    seed_blocks : list[dict]
        Each dict has keys: table, columns (list[str]), rows (list[list[str]]).

    Returns
    -------
    list[dict] with keys: table, columns, rows — ready for template iteration.
    """
    return [
        {
            "table": s["table"],
            "columns": s["columns"],
            "rows": s["rows"],
        }
        for s in seed_blocks
    ]


# ---------------------------------------------------------------------------
# Query context builder
# ---------------------------------------------------------------------------


def build_query_context(query_blocks: list[dict]) -> list[dict]:
    """Convert parsed query blocks into template-ready query contexts.

    Parameters
    ----------
    query_blocks : list[dict]
        Each dict has keys: name, sql.

    Returns
    -------
    list[dict] with keys: name, sql.
    """
    return [{"name": q["name"], "sql": q["sql"]} for q in query_blocks]
