import type { PiSshConfig, SshHostConfig } from "./config.ts";

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 as a sequential state transition. Use this as a separate step when the user names a remote server as part of a concrete task, and wait for success before calling dependent ssh_* tools; 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,
  },
  executionMode: "sequential",
} 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 };
}

export function getConfiguredHost(config: PiSshConfig, hostId: string): SshHostConfig {
  const host = config.hosts[hostId];
  if (host) return host;
  const hostIds = Object.keys(config.hosts).sort();
  if (hostIds.length === 0) {
    throw new Error(`unknown pi-ssh host '${hostId}'; no hosts are imported; run ssh_config.sh import <alias>`);
  }
  const shown = hostIds.slice(0, 10);
  const remaining = hostIds.length - shown.length;
  const available = `${shown.join(", ")}${remaining > 0 ? `, … (+${remaining} more)` : ""}`;
  throw new Error(`unknown pi-ssh host '${hostId}'; available imported host IDs: ${available}`);
}
