import json

import jingrow


def execute():
	jingrow.reload_pg("jcloud", "pagetype", "site")
	jingrow.reload_pg("jcloud", "pagetype", "site config")
	sites = jingrow.get_all("Site", {"status": ("!=", "Archived")})

	commit_scheme = jingrow.db.auto_commit_on_many_writes
	jingrow.db.auto_commit_on_many_writes = 1

	for _site in sites:
		site = jingrow.get_pg("Site", _site.name)
		if site.configuration:
			continue
		print(f"Updating Site Config for {site.name}")
		config = json.loads(site.config)
		for key, value in config.items():
			if isinstance(value, (dict, list)):
				value = json.dumps(value)
			else:
				value = value
			site.append("configuration", {"key": key, "value": value})
		site.save()

	jingrow.db.auto_commit_on_many_writes = commit_scheme
