# Copyright (c) 2022, JINGROW and Contributors
# License: MIT. See LICENSE

from contextlib import suppress

import jingrow
from jingrow import _
from jingrow.query_builder.functions import DateFormat, Function
from jingrow.query_builder.utils import PageType
from jingrow.utils.data import add_to_date, cstr, flt, now_datetime
from jingrow.utils.formatters import format_value


def get_monthly_results(
	goal_pagetype: str,
	goal_field: str,
	date_col: str,
	filters: dict,
	aggregation: str = "sum",
) -> dict:
	"""Get monthly aggregation values for given field of pagetype"""

	Table = PageType(goal_pagetype)
	date_format = "%m-%Y" if jingrow.db.db_type != "postgres" else "MM-YYYY"

	return dict(
		jingrow.qb.get_query(
			table=goal_pagetype,
			fields=[
				DateFormat(Table[date_col], date_format).as_("month_year"),
				Function(aggregation, goal_field),
			],
			filters=filters,
			validate_filters=True,
		)
		.groupby("month_year")
		.run()
	)


@jingrow.whitelist()
def get_monthly_goal_graph_data(
	title: str,
	pagetype: str,
	pagename: str,
	goal_value_field: str,
	goal_total_field: str,
	goal_history_field: str,
	goal_pagetype: str,
	goal_pagetype_link: str,
	goal_field: str,
	date_field: str,
	aggregation: str = "sum",
	filters: str | dict | None = None,
) -> dict:
	"""
	Get month-wise graph data for a pagetype based on aggregation values of a field in the goal pagetype

	:param title: Graph title
	:param pagetype: pagetype of graph pg
	:param pagename: of the pg to set the graph in
	:param goal_value_field: goal field of pagetype
	:param goal_total_field: current month value field of pagetype
	:param goal_history_field: cached history field
	:param goal_pagetype: pagetype the goal is based on
	:param goal_pagetype_link: pagetype link field in goal_pagetype
	:param goal_field: field from which the goal is calculated
	:param aggregation: a value like 'count', 'sum', 'avg'
	:param filters: optional filters

	:return: dict of graph data
	"""
	pg = jingrow.get_pg(pagetype, pagename)
	pg.check_permission()

	meta = pg.meta
	goal = pg.get(goal_value_field)
	today_date = now_datetime().date()

	current_month_value = pg.get(goal_total_field)
	current_month_year = today_date.strftime("%m-%Y")  # eg: "02-2022"
	formatted_value = format_value(current_month_value, meta.get_field(goal_total_field), pg)
	history = pg.get(goal_history_field)

	month_to_value_dict = None
	if history and "{" in cstr(history):
		with suppress(ValueError):
			month_to_value_dict = jingrow.parse_json(history)

	if month_to_value_dict is None:  # nosemgrep
		pg_filter = {}
		with suppress(ValueError):
			pg_filter = jingrow.parse_json(filters or "{}")
		if pagetype != goal_pagetype:
			pg_filter[goal_pagetype_link] = pagename

		month_to_value_dict = get_monthly_results(
			goal_pagetype, goal_field, date_field, pg_filter, aggregation
		)

	month_to_value_dict[current_month_year] = current_month_value

	month_labels = []
	dataset_values = []
	values_formatted = []
	y_markers = {}

	summary_values = [
		{"title": _("This month"), "color": "#ffa00a", "value": formatted_value},
	]

	if flt(goal) > 0:
		formatted_goal = format_value(goal, meta.get_field(goal_value_field), pg)
		summary_values += [
			{"title": _("Goal"), "color": "#5e64ff", "value": formatted_goal},
			{
				"title": _("Completed"),
				"color": "#28a745",
				"value": f"{int(round(flt(current_month_value) / flt(goal) * 100))}%",
			},
		]
		y_markers = {"yMarkers": [{"label": _("Goal"), "lineType": "dashed", "value": flt(goal)}]}

	for i in range(12):
		date_value = add_to_date(today_date, months=-i, as_datetime=True)
		month_word = date_value.strftime("%b %y")  # eg: "Feb 22"
		month_labels.insert(0, month_word)

		month_value = date_value.strftime("%m-%Y")  # eg: "02-2022"
		val = month_to_value_dict.get(month_value, 0)
		dataset_values.insert(0, val)
		values_formatted.insert(0, format_value(val, meta.get_field(goal_total_field), pg))

	return {
		"title": title,
		"data": {
			"datasets": [{"values": dataset_values, "formatted": values_formatted}],
			"labels": month_labels,
			**y_markers,
		},
		"summary": summary_values,
	}
