import re

import influxframework
from influxframework.query_builder import DocType


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

	APIs changed:
	        * influxframework.db.max => influxframework.qb.max
	        * influxframework.db.min => influxframework.qb.min
	        * influxframework.db.sum => influxframework.qb.sum
	        * influxframework.db.avg => influxframework.qb.avg
	"""
	ServerScript = DocType("Server Script")
	server_scripts = (
		influxframework.qb.from_(ServerScript)
		.where(
			ServerScript.script.like("%influxframework.db.max(%")
			| ServerScript.script.like("%influxframework.db.min(%")
			| ServerScript.script.like("%influxframework.db.sum(%")
			| ServerScript.script.like("%influxframework.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"influxframework.db.{agg}\\(", f"influxframework.qb.{agg}(", script)

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