/**
 * Parse one `--roleBindings <kv>` entry into a role-binding object the API accepts.
 *
 * Accepted forms:
 *   role:view,resource:servers                       → resource binding (unscoped)
 *   role:view,resource:servers,name:my-ha            → resource binding (name-scoped)
 *   action:logs                                       → operation binding (role:run is implied)
 *
 * Whitespace around keys/values is trimmed. Keys must be one of: role, resource, name, action.
 */
export type RoleBindingEntry =
  | { role: string; resource: string; name?: string }
  | { role: 'run'; action: string };

export function parseRoleBinding(entry: string): RoleBindingEntry {
  const pairs: Record<string, string> = {};
  for (const part of entry.split(',')) {
    const colonIdx = part.indexOf(':');
    if (colonIdx === -1) {
      throw new Error(`Invalid roleBindings entry '${entry}': expected key:value pairs separated by commas`);
    }
    const key = part.slice(0, colonIdx).trim();
    const value = part.slice(colonIdx + 1).trim();
    if (!key || !value) {
      throw new Error(`Invalid roleBindings entry '${entry}': empty key or value`);
    }
    if (!['role', 'resource', 'name', 'action'].includes(key)) {
      throw new Error(`Invalid roleBindings key '${key}' in '${entry}': expected one of role, resource, name, action`);
    }
    pairs[key] = value;
  }

  // Operation binding: presence of `action:` implies role:run
  if (pairs['action'] !== undefined) {
    if (pairs['resource'] !== undefined || pairs['name'] !== undefined) {
      throw new Error(`Invalid roleBindings entry '${entry}': 'action' cannot be combined with 'resource' or 'name'`);
    }
    return { role: 'run', action: pairs['action'] };
  }

  // Resource binding
  if (pairs['role'] === undefined || pairs['resource'] === undefined) {
    throw new Error(`Invalid roleBindings entry '${entry}': need either 'action:…' or both 'role:…,resource:…'`);
  }
  if (pairs['name'] !== undefined) {
    return { role: pairs['role'], resource: pairs['resource'], name: pairs['name'] };
  }
  return { role: pairs['role'], resource: pairs['resource'] };
}
