How do you add a category to a post in code

There’s the wp_update_post(), also.

According to categories, please refer to the documentation.

Categories need to be passed as an array of integers that match the
category IDs in the database. This is the case even where only one
category is assigned to the post.

So, it would be something like:

$post = get_post($i = $post_id);
$post->post_category = array ($cat1, $cat2, $cat3);
wp_update_post($post);