"""Manual components — too complex for codegen."""
from __future__ import annotations

import builtins
from typing import Any

from zuzu.runtime.spec import _add_component
from zuzu.record import Record, RecordQuery
from zuzu.components._generated.display import text, metric, list, grid

builtins_list = builtins.list


def write(value: Any) -> None:
    """Magic function — auto-detects type and renders appropriately."""
    if isinstance(value, str):
        text(value)
    elif isinstance(value, (int, float)):
        metric("", value)
    elif isinstance(value, dict):
        _add_component({"type": "json", "data": value})
    elif isinstance(value, builtins_list) and len(value) > 0 and isinstance(value[0], dict):
        grid(value)
    elif isinstance(value, Record):
        list(value, title=next(iter(value._fields), None))
    elif isinstance(value, RecordQuery):
        list(value)
    else:
        text(str(value))


def form(
    title: str,
    *,
    table: Record | None = None,
    fields: builtins_list[dict[str, Any]] | None = None,
    on_submit: Any | None = None,
    defaults: dict[str, Any] | None = None,
) -> None:
    comp: dict[str, Any] = {"type": "form", "title": title}
    if table:
        comp["table"] = table._table_name
    if fields:
        comp["fields"] = fields
    if defaults:
        comp["defaults"] = defaults
    _add_component(comp)
