"""
Compute InChIs from species-key where they are still missing.

If all is well, replace the previous file.
"""

from gavo.protocols import linetap


def add_inchi(parts):
	ilib = linetap.getILib()
	if len(parts)==3:
		parsed, inchi = ilib.getInChIFromCode(parts[2])
		inchikey = ilib.getInChIKey(inchi)
		return parts+[inchi, inchikey, str(parsed.getTotalWeight())]
	else:
		return parts


to_write = []
dest_name = "res/species-key.txt"
with open(dest_name, "r", encoding="utf-8") as in_f:
	try:
		for l in in_f:
			parts = l.strip().split("\t")

			if len(parts)==6:
				to_write.append(parts)
			else:
				to_write.append(add_inchi(parts))
	except Exception:
		print(">>>>>>>>>>", l)
		raise

with open(dest_name, "w", encoding="utf-8") as out_f:
	out_f.write("\n".join("\t".join(l) for l in to_write)+"\n")
