import { classifySshTcpPoolFailure, type SshCaptureResult } from "./ssh";

export function remoteGcDegradedFailure(providerId: string, action: string, result: SshCaptureResult): Record<string, unknown> {
  const text = `${result.stderr}\n${result.stdout}`;
  const failureKind = classifySshTcpPoolFailure(text);
  const timeout = result.exitCode === 124 || text.includes("ssh-runtime-timeout");
  const providerOffline = text.includes(`provider is not online: ${providerId}`) || text.includes("provider is not online");
  const degradedReason = failureKind ?? (providerOffline ? "provider-offline" : timeout ? "ssh-runtime-timeout" : "remote-command-failed");
  return {
    ok: false,
    degraded: true,
    providerId,
    action: `gc remote ${action}`,
    degradedReason,
    transport: {
      sshTcpPoolFailureKind: failureKind,
      providerOffline,
      sshRuntimeTimeout: timeout,
      exitCode: result.exitCode,
    },
    safeCandidateCount: null,
    runAllowed: false,
    mutation: false,
    summary: failureKind !== null
      ? `remote GC could not acquire a provider data channel: ${failureKind}`
      : providerOffline
        ? `provider ${providerId} is offline from the controlled CLI transport view`
        : timeout
          ? "remote GC did not complete before the SSH runtime timeout"
          : "remote GC command failed before producing a valid plan",
    next: {
      sshPool: `bun scripts/cli.ts debug ssh-pool ${providerId}`,
      fullHealth: "bun scripts/cli.ts debug health",
      smoke: `trans ${providerId} argv true`,
      retryPlan: `bun scripts/cli.ts gc remote ${providerId} plan --no-snapshot-save`,
    },
  };
}
