import jingrow
from jingrow.core.pagetype.log_settings.log_settings import clear_log_table
from jingrow.utils import add_to_date, today


def execute():
	"""Due to large size of log tables on old sites some table cleanups never finished during daily log clean up. This patch discards such data by using "big delete" code.

	ref: http://git.jingrow.com/jingrow/jingrow/issues/16971
	"""

	PAGETYPE_RETENTION_MAP = {
		"Error Log": get_current_setting("clear_error_log_after") or 90,
		"System Log": get_current_setting("clear_system_log_after") or 90,
		"Email Queue": get_current_setting("clear_email_queue_after") or 30,
		# child table on email queue
		"Email Queue Recipient": get_current_setting("clear_email_queue_after") or 30,
		# newly added
		"Scheduled Job Log": 90,
	}

	for pagetype, retention in PAGETYPE_RETENTION_MAP.items():
		if is_log_cleanup_stuck(pagetype, retention):
			print(f"Clearing old {pagetype} records")
			clear_log_table(pagetype, retention)


def is_log_cleanup_stuck(pagetype: str, retention: int) -> bool:
	"""Check if pagetype has data significantly older than configured cleanup period"""
	threshold = add_to_date(today(), days=retention * -2)

	return bool(jingrow.db.exists(pagetype, {"modified": ("<", threshold)}))


def get_current_setting(fieldname):
	try:
		return jingrow.db.get_single_value("Log Settings", fieldname)
	except Exception:
		# Field might be gone if patch is reattempted
		pass
