Figuring out "exactly what the law tells you to do" is the tricky part. The law merely prescribes the step-by-step instructions for each form. It will not explain the emergent behavior that you'll need to know to optimize your way through the system. It will not advise you ahead of time to do things like spend no more than 30 days in the US to qualify as a foreign resident. You wouldn't even know that's a relevant question to ask unless informed by a suitable expert.
This sort of thing is the financial engineering that patio11 is talking about. It's not cheating, it's doing what the system is meant to let you do, if only you understood the best paths through the system.
I have a similar situation on a smaller scale. I live in one US state and work in another. I file income tax for both, and there's a form that takes my tax liability to my state of work and backs it out of my liability to my state of residence. I wouldn't have known that form existed and would have just assumed I had to pay full tax to both states, if not for TurboTax directing me to that form.
The law will direct you how to mechanically comply, but it won't direct you against complying in ways hurtful to yourself.