Ionic Compound Golf

Lua, 174 242 bytes

I forgot the brackets '-_-, that got me up to 242. Oh well, it was a fun enough challenge at least.

i,c,a={Ba=2,Ca=2,Cu=2,Mg=2,Zn=2,Pb=2,Fe=3,Al=3,O=2,S=2,SO4=2,CO3=2},io.read(),io.read()
p,d=i[c]~=i[a],{SO4=1,NO3=1,OH=1,CO3=1}
k,m=p and i[c]or'',p and i[a]or''
a=k==m and a or (d[a]and'('..a..')'or a)
print(c..a=='HOH'and'H2O'or c..m..a..k)

Try it online!

Old version:

i,c,a={Ba=2,Ca=2,Cu=2,Mg=2,Zn=2,Pb=2,Fe=3,Al=3,O=2,S=2,SO4=2,CO3=2},io.read(),io.read()
p=i[c]~=i[a]
k,m=p and i[c]or'',p and i[a]or''
print(c..a=='HOH'and'H2O'or c..m..a..k)

Abusing Lua's tendency to initialize everything with a nil value we can cut down on storage costs. Still, Lua is still a bit clunky :(