import re

import xhiveframework
from xhiveframework.query_builder import DocType


def execute():
	"""Replace temporarily available Database Aggregate APIs on xhiveframework (develop)

	APIs changed:
	        * xhiveframework.db.max => xhiveframework.qb.max
	        * xhiveframework.db.min => xhiveframework.qb.min
	        * xhiveframework.db.sum => xhiveframework.qb.sum
	        * xhiveframework.db.avg => xhiveframework.qb.avg
	"""
	ServerScript = DocType("Server Script")
	server_scripts = (
		xhiveframework.qb.from_(ServerScript)
		.where(
			ServerScript.script.like("%xhiveframework.db.max(%")
			| ServerScript.script.like("%xhiveframework.db.min(%")
			| ServerScript.script.like("%xhiveframework.db.sum(%")
			| ServerScript.script.like("%xhiveframework.db.avg(%")
		)
		.select("name", "script")
		.run(as_dict=True)
	)

	for server_script in server_scripts:
		name, script = server_script["name"], server_script["script"]

		for agg in ["avg", "max", "min", "sum"]:
			script = re.sub(f"xhiveframework.db.{agg}\\(", f"xhiveframework.qb.{agg}(", script)

		xhiveframework.db.update("Server Script", name, "script", script)
