When to use 了 and 的? 了 is used after verb or sentence to indicate that something has been finished/done or something has changed.

的 is used in many cases, one of which is to indicate the speaker's modality of certainty.

他来了。 He has come. (O)  -> 了 needs to be used.

他来的。 (X) -> 的 should not be used.

他现在才来了（X) -> Now, 了 should not be used in this case.

他现在才来的。He has just come. (O) -> Now, 的 needs to be used in this case.

Apparently there is some rule that I am missing, which makes me quite confused about how exactly these 了 and 的 work.

It will be really nice if I can tell which one is an appropriate one when I write things in Mandarin.

Thanks in advance.
他（是）现在才来的 is a 是的 construction for emphasis. In this case, 是 is omitted. He has arrived just now, in this very moment!

Another example: 我是来看病的: I have come to have a health check (rather than just socialize).

他来了 just indicates he has arrived, without emphasis. 了 completes the statement.