import type { UniDeskConfig } from "../config";
import { resolveAgentRunLaneTarget } from "../agentrun-lanes";
import { runSshCommandCapture } from "../ssh";
import { readAgentRunClientConfig } from "./config";
import {
  AgentRunTargetTaskPreflightError,
  preflightTargetTaskFromObservedWorkspace,
  targetTaskRequestFromArgs,
  type AgentRunTargetTaskPreflight,
} from "./target-task";
import type { AgentRunResourceOptions } from "./utils";

export async function prepareAgentRunTargetTaskPreflight(
  config: UniDeskConfig | null,
  canonicalArgs: string[],
  options: AgentRunResourceOptions,
): Promise<AgentRunTargetTaskPreflight | null> {
  const request = targetTaskRequestFromArgs(canonicalArgs);
  if (request === null) return null;
  const client = readAgentRunClientConfig();
  if (client.client.transport !== "target-trans") {
    throw new AgentRunTargetTaskPreflightError(
      "target-execution",
      `${client.sourcePath} 必须声明 client.transport=target-trans。`,
      { configPath: client.sourcePath, transport: client.client.transport },
    );
  }
  if (config === null) {
    throw new AgentRunTargetTaskPreflightError(
      "target-execution",
      "Artificer Target 派单需要 UniDesk 配置以执行受控目录探测。",
      { target: request.target, targetWorkspace: request.targetWorkspace },
    );
  }
  const { spec } = resolveAgentRunLaneTarget({ node: options.node, lane: options.lane });
  if (request.target !== spec.nodeId) {
    throw new AgentRunTargetTaskPreflightError(
      "target-context",
      `--target ${request.target} 与选中 AgentRun lane 的 Target ${spec.nodeId} 不一致。`,
      { target: request.target, selectedTarget: spec.nodeId, lane: spec.lane },
    );
  }

  const route = `${spec.nodeRoute}:${request.targetWorkspace}`;
  const capture = await runSshCommandCapture(config, route, ["argv", "pwd", "-P"]);
  const workspaceRoot = capture.stdout.trim();
  if (capture.exitCode !== 0 || workspaceRoot.length === 0) {
    throw new AgentRunTargetTaskPreflightError(
      "workspace",
      `Target 工作区不存在或不是目录：${request.target}:${request.targetWorkspace}`,
      {
        target: request.target,
        targetWorkspace: request.targetWorkspace,
        route,
        exitCode: capture.exitCode,
      },
    );
  }
  return preflightTargetTaskFromObservedWorkspace(request, workspaceRoot);
}
