from __future__ import annotations

from typing import Any

from aicd.env_probe import (
    build_environment_digest,
    capabilities_summary_path,
    load_runtime_env_snapshot,
    refresh_runtime_env_file,
    runtime_env_path,
    summarize_commands,
)


def _runtime_env_refresh(router: Any, args: dict[str, Any]) -> dict[str, Any]:
    del args  # 无参数；保留以兼容 OpenAI tools schema
    path, data = refresh_runtime_env_file(router._layout)
    router.notify_env_capabilities_updated(data, path)
    avail, total = summarize_commands(data)
    return {
        "ok": True,
        "path": str(path),
        "capabilities_summary_path": str(capabilities_summary_path(router._layout)),
        "generated_at": data.get("generated_at"),
        "commands_available": avail,
        "commands_total": total,
        "hint": "Use fs_read_file on path for full YAML; capabilities_summary_path mirrors the model-facing "
        "snapshot; call again after user installs tools.",
    }


def _agent_environment_digest(router: Any, args: dict[str, Any]) -> dict[str, Any]:
    layout = router._layout
    refresh_first = bool(args.get("refresh_first", False))
    if refresh_first:
        path, data = refresh_runtime_env_file(layout)
        router.notify_env_capabilities_updated(data, path)
    else:
        data = load_runtime_env_snapshot(layout)

    cfg = router._cfg
    yp = str(runtime_env_path(layout).resolve())
    cap_p = str(capabilities_summary_path(layout).resolve())
    ai_out, ai_tmp = router.get_ai_paths()
    digest = build_environment_digest(
        data,
        ai_workspace_cwd=str(router.cwd.resolve()),
        ai_output_root=str(ai_out),
        ai_tmp_dir=str(ai_tmp),
        runtime_yaml_path=yp,
        capabilities_summary_path_str=cap_p,
        agent_max_tool_rounds=int(cfg.agent.max_tool_rounds),
        sub_agent_max_tool_rounds=int(cfg.agent.sub_agent_max_tool_rounds),
        llm_proto=str(cfg.llm.proto),
        llm_model=str(cfg.llm.model),
        llm_api_key_configured=bool(str(cfg.llm.api_key or "").strip()),
    )
    avail, total = summarize_commands(data)
    out: dict[str, Any] = {
        "ok": True,
        "generated_at": data.get("generated_at"),
        "commands_available": avail,
        "commands_total": total,
        **digest,
    }
    if args.get("include_capabilities_text"):
        cap = capabilities_summary_path(layout)
        mc = int(args.get("capabilities_max_chars", 6000) or 6000)
        mc = max(500, min(12000, mc))
        if cap.is_file():
            txt = cap.read_text(encoding="utf-8", errors="replace")
            out["capabilities_summary_excerpt"] = txt[:mc]
        else:
            out["capabilities_summary_excerpt"] = ""
    return out


HANDLERS: dict[str, Any] = {
    "runtime_env_refresh": _runtime_env_refresh,
    "agent_environment_digest": _agent_environment_digest,
}
