// SPEC: PJ2026-010405 云端控制台；PJ2026-010103 HWPOD 服务。
// Implementation reference: draft-2026-07-13-p0-cloud-console。
// Responsibility: 调用 HWPOD typed topology、显式 readiness probe 与 Python Node 更新元数据接口。

import { fetchJson } from "./client";
import type {
  ApiResult,
  HwpodDeviceTopologyItem,
  HwpodNodeOpsResponse,
  HwpodNodeTopologyItem,
  HwpodOperationResponse,
  HwpodSpecsResponse,
  HwpodTopologyResponse,
  HwlabNodeUpdateMetadata
} from "@/types";

export interface TopologyQuery {
  q?: string;
  status?: string;
  sort?: "name" | "status" | "lastSeenAt" | "deviceCount";
  direction?: "asc" | "desc";
  cursor?: string;
  limit?: number;
  probe?: boolean;
}

function topologyPath(resource: "device" | "node", query: TopologyQuery = {}): string {
  const params = new URLSearchParams({ resource, sort: query.sort ?? "name", direction: query.direction ?? "asc", limit: String(query.limit ?? 50) });
  if (query.probe) params.set("probe", "1");
  if (query.q?.trim()) params.set("q", query.q.trim());
  if (query.status?.trim()) params.set("status", query.status.trim());
  if (query.cursor?.trim()) params.set("cursor", query.cursor.trim());
  return `/v1/hwpod/topology?${params.toString()}`;
}

export const hwpodAPI = {
  specs: (): Promise<ApiResult<HwpodSpecsResponse>> => fetchJson("/v1/hwpod/specs?probe=1", { timeoutMs: 12000, timeoutName: "HWPOD specs" }),
  nodeOpsHealth: (): Promise<ApiResult<HwpodNodeOpsResponse>> => fetchJson("/v1/hwpod-node-ops", { timeoutMs: 12000, timeoutName: "HWPOD node-ops" }),
  groups: (): Promise<ApiResult<HwpodNodeOpsResponse>> => fetchJson("/v1/hwpod-node-ops", { timeoutMs: 12000, timeoutName: "HWPOD groups" }),
  devices: (query: TopologyQuery = {}): Promise<ApiResult<HwpodTopologyResponse<HwpodDeviceTopologyItem>>> => fetchJson(topologyPath("device", query), { timeoutMs: 20000, timeoutName: "HWPOD device topology" }),
  nodes: (query: TopologyQuery = {}): Promise<ApiResult<HwpodTopologyResponse<HwpodNodeTopologyItem>>> => fetchJson(topologyPath("node", query), { timeoutMs: 20000, timeoutName: "HWPOD node topology" }),
  nodeUpdate: (): Promise<ApiResult<HwlabNodeUpdateMetadata>> => fetchJson("/v1/hwlab-node/update?platform=windows&channel=stable", { timeoutMs: 12000, timeoutName: "HWLAB Node update metadata" }),
  startOperation: (input: { hwpodId: string; intent: string; args?: Record<string, unknown> }): Promise<ApiResult<HwpodOperationResponse>> => fetchJson("/v1/hwpod/operations", { method: "POST", body: JSON.stringify(input), timeoutMs: 12000, timeoutName: "HWPOD operation submit" }),
  operation: (operationId: string): Promise<ApiResult<HwpodOperationResponse>> => fetchJson(`/v1/hwpod/operations/${encodeURIComponent(operationId)}`, { timeoutMs: 12000, timeoutName: "HWPOD operation status" })
};
