from typing import Any, Dict, Sequence

from cmdlet._shared import Cmdlet, CmdletArg
from SYS.logger import log


def _run(piped_result: Any, args: Sequence[str], config: Dict[str, Any]) -> int:
    # Debug utility: dump current pipeline table state (display/current/last + buffers)
    try:
        from SYS import pipeline as ctx
    except Exception as exc:
        log(f"Failed to import pipeline context: {exc}")
        return 1

    state = None
    try:
        state = ctx.get_pipeline_state() if hasattr(ctx, "get_pipeline_state") else None
    except Exception:
        state = None

    def _summarize_table(name: str, t: Any) -> None:
        if t is None:
            print(f"{name}: None")
            return
        try:
            table_type = getattr(t, "table", None)
        except Exception:
            table_type = None
        try:
            title = getattr(t, "title", None)
        except Exception:
            title = None
        try:
            src_cmd = getattr(t, "source_command", None)
        except Exception:
            src_cmd = None
        try:
            src_args = getattr(t, "source_args", None)
        except Exception:
            src_args = None
        try:
            no_choice = bool(getattr(t, "no_choice", False))
        except Exception:
            no_choice = False
        try:
            preserve_order = bool(getattr(t, "preserve_order", False))
        except Exception:
            preserve_order = False
        try:
            row_count = len(getattr(t, "rows", []) or [])
        except Exception:
            row_count = 0
        try:
            meta = (
                t.get_table_metadata() if hasattr(t, "get_table_metadata") else getattr(t, "table_metadata", None)
            )
        except Exception:
            meta = None
        meta_keys = list(meta.keys()) if isinstance(meta, dict) else []

        print(
            f"{name}: id={id(t)} class={type(t).__name__} title={repr(title)} table={repr(table_type)} rows={row_count} "
            f"source={repr(src_cmd)} source_args={repr(src_args)} no_choice={no_choice} preserve_order={preserve_order} meta_keys={meta_keys}"
        )

    label = ""
    try:
        label = str(args[0]) if args else ""
        if label:
            print(f"Table State: {label}")
        else:
            print("Table State")
    except Exception:
        print("Table State")

    try:
        _summarize_table("display_table", getattr(state, "display_table", None) if state is not None else None)
        _summarize_table("current_stage_table", getattr(state, "current_stage_table", None) if state is not None else None)
        _summarize_table("last_result_table", getattr(state, "last_result_table", None) if state is not None else None)

        display_items = getattr(state, "display_items", None) if state is not None else None
        last_result_items = getattr(state, "last_result_items", None) if state is not None else None
        hist = getattr(state, "result_table_history", None) if state is not None else None
        fwd = getattr(state, "result_table_forward", None) if state is not None else None
        last_sel = getattr(state, "last_selection", None) if state is not None else None

        print(
            "buffers: "
            f"display_items={len(display_items or [])} "
            f"last_result_items={len(last_result_items or [])} "
            f"history={len(hist or [])} "
            f"forward={len(fwd or [])} "
            f"last_selection={list(last_sel or [])}"
        )
    except Exception as exc:
        log(f"Failed to summarize table state: {exc}")
        return 1

    # If debug logging is enabled, also emit the richer debug dump.
    try:
        if hasattr(ctx, "debug_table_state"):
            ctx.debug_table_state(label or ".table")
    except Exception:
        pass

    return 0


CMDLET = Cmdlet(
    name=".table",
    summary="Dump pipeline table state for debugging",
    usage=".table [label]",
    arg=[
        CmdletArg(
            name="label",
            type="string",
            description="Optional label to include in the dump",
            required=False,
        ),
    ],
)

CMDLET.exec = _run
