import jingrow
import jingrow.utils

from jcloude import utils as jcloude_utils
from jcloude.access import utils as access_utils
from jcloude.access.actions import ReleaseGroupActions, SiteActions

TAB_DF_MAP = {
	"Site": {
		"Domains": "site_domains",
	},
}

ACTION_DF_MAP = {
	"Release Group": {
		ReleaseGroupActions.SSHAccess.value: "bench_ssh",
	},
	"Site": {
		SiteActions.LoginAsAdmin.value: "login_as_administrator",
	},
}


def get_extra_field(pagetype: str, perm: str | None) -> str | None:
	if not perm:
		return None
	if field := TAB_DF_MAP.get(pagetype, {}).get(perm):
		return field
	if field := ACTION_DF_MAP.get(pagetype, {}).get(perm):
		return field
	return None


def has_support_access(pagetype: str, docname: str, action: str | None = None) -> bool:
	"""
	Checks if current team has support access to given document.
	"""

	if jingrow.local.system_user():
		return True

	if not jcloude_utils.has_role("Jcloude Support Agent"):
		return False

	if access_utils.is_public_resource(pagetype, docname):
		return True

	filters = {
		"status": "Accepted",
		"access_allowed_till": (">", jingrow.utils.now_datetime()),
	}

	if field := get_extra_field(pagetype, action):
		filters[field] = 1

	accesses = jingrow.get_all("Support Access", filters=filters, pluck="name")

	for access in accesses:
		if jingrow.db.exists(
			"Support Access Resource",
			{
				"parent": access,
				"document_type": pagetype,
				"document_name": docname,
			},
		):
			return True

	return False
