export interface HostSelection {
  hostId: string;
  remotePath?: string;
}

export const SSH_CONNECT_TOOL_METADATA = {
  name: "ssh_connect",
  label: "ssh_connect",
  description: "Establish a persistent SSH2 connection to an explicitly imported host. Use this when the user names a remote server as part of a concrete task; the connection request is reviewed before any network connection is opened.",
  parameters: {
    type: "object",
    properties: {
      hostId: { type: "string", description: "Imported pi-ssh host ID explicitly named by the user" },
      remotePath: { type: "string", description: "Optional remote cwd; must be absolute, ~, or start with ~/" },
    },
    required: ["hostId"],
    additionalProperties: false,
  },
} as const;

export function parseConnectInput(input: Record<string, unknown>): HostSelection {
  const hostId = typeof input.hostId === "string" ? input.hostId.trim() : "";
  if (!hostId) throw new Error("SSH host id is required");
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(hostId)) throw new Error(`invalid pi-ssh host id: ${hostId}`);

  if (input.remotePath === undefined) return { hostId };
  if (typeof input.remotePath !== "string") throw new Error("remote path must be a string");
  const remotePath = input.remotePath.trim();
  if (!remotePath || !(remotePath === "~" || remotePath.startsWith("~/") || remotePath.startsWith("/"))) {
    throw new Error("remote path must be absolute or start with ~/");
  }
  return { hostId, remotePath };
}
