from __future__ import annotations

from typing import TYPE_CHECKING, Any

from aicd.kit import (
    crypto_codec,
    format_data,
    math_stats,
    script_templates,
    text_regex,
    time_log,
)

if TYPE_CHECKING:
    from aicd.agent.tool_router import ToolRouter


def _data_stats(router: ToolRouter, args: dict[str, Any]) -> dict[str, Any]:
    op = str(args.get("operation") or "")
    payload = {k: v for k, v in args.items() if k != "operation"}
    return math_stats.run_operation(op, payload)


def _data_text(router: ToolRouter, args: dict[str, Any]) -> dict[str, Any]:
    op = str(args.get("operation") or "")
    payload = {k: v for k, v in args.items() if k != "operation"}
    return text_regex.run_operation(op, payload)


def _data_time(router: ToolRouter, args: dict[str, Any]) -> dict[str, Any]:
    op = str(args.get("operation") or "")
    payload = {k: v for k, v in args.items() if k not in ("operation", "append_jsonl_path")}
    result = time_log.run_operation(op, payload)
    path_str = args.get("append_jsonl_path")
    if path_str and result.get("ok") and op == "log_record":
        rec = result.get("record")
        if isinstance(rec, dict):
            p = router._resolve_path(str(path_str))
            p.parent.mkdir(parents=True, exist_ok=True)
            time_log.append_jsonl(str(p), rec)
            result = {**result, "appended_jsonl": str(p)}
    return result


def _script_template(_router: ToolRouter, args: dict[str, Any]) -> dict[str, Any]:
    return script_templates.render(str(args.get("shell") or ""), str(args.get("intent") or ""))


def _data_crypto(_router: ToolRouter, args: dict[str, Any]) -> dict[str, Any]:
    op = str(args.get("operation") or "")
    payload = {k: v for k, v in args.items() if k != "operation"}
    return crypto_codec.run_operation(op, payload)


def _data_format(_router: ToolRouter, args: dict[str, Any]) -> dict[str, Any]:
    op = str(args.get("operation") or "")
    payload = {k: v for k, v in args.items() if k != "operation"}
    return format_data.run_operation(op, payload)


HANDLERS: dict[str, Any] = {
    "data_stats": _data_stats,
    "data_text": _data_text,
    "data_time": _data_time,
    "data_crypto": _data_crypto,
    "data_format": _data_format,
    "script_template": _script_template,
}
