# Copyright (c) 2024, JINGROW
# For license information, please see license.txt
import jingrow
from tqdm import tqdm


def execute():
	key_name = "plan_limit"
	if not jingrow.db.exists("Site Config Key", {"key": key_name}):
		jingrow.get_pg(
			{
				"pagetype": "Site Config Key",
				"key": key_name,
				"type": "JSON",
				"internal": True,
			}
		).insert(ignore_permissions=True)

	non_archived_sites = jingrow.get_all(
		"Site", filters={"status": ("!=", "Archived")}, pluck="name"
	)

	for site_name in tqdm(non_archived_sites):
		try:
			site = jingrow.get_pg("Site", site_name, for_update=True)
			site.update_site_config(site.get_plan_config())
			jingrow.db.commit()
		except Exception as e:
			print(f"Couldn't set plan limit for site {site_name}: {e}")
			jingrow.db.rollback()
