# Copyright (c) 2019, JINGROW
# For license information, please see license.txt
from __future__ import annotations

import re
from collections import OrderedDict
from typing import TYPE_CHECKING

import jingrow
from jingrow.core.utils import find, find_all
from jingrow.model.naming import append_number_if_name_exists
from jingrow.utils import flt, sbool

from jcloud.api.github import branches
from jcloud.api.site import protected
from jcloud.jcloud.pagetype.agent_job.agent_job import job_detail
from jcloud.jcloud.pagetype.app_patch.app_patch import create_app_patch
from jcloud.jcloud.pagetype.bench_update.bench_update import get_bench_update
from jcloud.jcloud.pagetype.cluster.cluster import Cluster
from jcloud.jcloud.pagetype.marketplace_app.marketplace_app import (
	get_total_installs_by_app,
)
from jcloud.jcloud.pagetype.release_group.release_group import (
	ReleaseGroup,
	new_release_group,
)
from jcloud.jcloud.pagetype.team.team import get_child_team_members
from jcloud.utils import (
	get_app_tag,
	get_client_blacklisted_keys,
	get_current_team,
	unique,
)

if TYPE_CHECKING:
	from jcloud.jcloud.pagetype.app_source.app_source import AppSource
	from jcloud.jcloud.pagetype.bench.bench import Bench
	from jcloud.jcloud.pagetype.deploy_candidate.deploy_candidate import DeployCandidate


@jingrow.whitelist()
def new(bench):
	team = get_current_team(get_pg=True)
	if not team.enabled:
		jingrow.throw("You cannot create a new bench because your account is disabled")

	if exists(bench["title"]):
		jingrow.throw("A bench exists with the same name")

	if bench["server"] and not (
		jingrow.session.data.user_type == "System User"
		or jingrow.db.get_value("Server", bench["server"], "team") == team.name
	):
		jingrow.throw("You can only create benches on your servers")

	apps = [{"app": app["name"], "source": app["source"]} for app in bench["apps"]]
	group = new_release_group(
		bench["title"],
		bench["version"],
		apps,
		team.name,
		bench["cluster"],
		bench["saas_app"] if jingrow.db.exists("Saas App", bench["saas_app"]) else "",
		bench["server"],
	)
	return group.name


@jingrow.whitelist()
@protected("Release Group")
def get(name):
	group = jingrow.get_pg("Release Group", name)
	return {
		"name": group.name,
		"title": group.title,
		"team": group.team,
		"version": group.version,
		"status": get_group_status(name),
		"last_updated": group.modified,
		"creation": group.creation,
		"saas_app": group.saas_app or "",
		"public": group.public,
		"no_sites": jingrow.db.count("Site", {"group": group.name, "status": "Active"}),
		"bench_tags": [{"name": x.tag, "tag": x.tag_name} for x in group.tags],
		"tags": jingrow.get_all(
			"Jcloud Tag", {"team": group.team, "pagetype_name": "Release Group"}, ["name", "tag"]
		),
	}


def get_group_status(name):
	active_benches = jingrow.get_all(
		"Bench", {"group": name, "status": "Active"}, limit=1, order_by="creation desc"
	)

	return "Active" if active_benches else "Awaiting Deploy"


@jingrow.whitelist()
def all(server=None, bench_filter=None):
	if bench_filter is None:
		bench_filter = {"status": "", "tag": ""}

	team = get_current_team()
	child_teams = [team.name for team in get_child_team_members(team)]
	teams = [team, *child_teams]

	group = jingrow.qb.PageType("Release Group")
	site = jingrow.qb.PageType("Site")
	query = (
		jingrow.qb.from_(group)
		.left_join(site)
		.on((site.group == group.name) & (site.status != "Archived"))
		.where((group.enabled == 1) & (group.public == 0))
		.where((group.team).isin(teams))
		.groupby(group.name)
		.select(
			jingrow.query_builder.functions.Count(site.name).as_("number_of_sites"),
			group.name,
			group.title,
			group.version,
			group.creation,
		)
		.orderby(group.title, order=jingrow.qb.desc)
	)

	bench = jingrow.qb.PageType("Bench")
	if bench_filter["status"] == "Active":
		query = query.inner_join(bench).on(group.name == bench.group)
	elif bench_filter["status"] == "Awaiting Deploy":
		group_names = jingrow.get_all("Bench", {"status": "Active"}, pluck="group", distinct=True)
		query = query.inner_join(bench).on(group.name.notin(group_names))
	if bench_filter["tag"]:
		jcloud_tag = jingrow.qb.PageType("Resource Tag")
		query = query.inner_join(jcloud_tag).on(
			(jcloud_tag.tag_name == bench_filter["tag"]) & (jcloud_tag.parent == group.name)
		)

	if server:
		group_server = jingrow.qb.PageType("Release Group Server")
		query = (
			query.inner_join(group_server)
			.on(group_server.parent == group.name)
			.where(group_server.server == server)
		)
	private_groups = query.run(as_dict=True)

	if not private_groups:
		return []

	app_counts = get_app_counts_for_groups([rg.name for rg in private_groups])
	for group in private_groups:
		group.tags = jingrow.get_all("Resource Tag", {"parent": group.name}, pluck="tag_name")
		group.number_of_apps = app_counts[group.name]
		group.status = get_group_status(group.name)

	return private_groups


@jingrow.whitelist()
def bench_tags():
	team = get_current_team()
	return jingrow.get_all("Jcloud Tag", {"team": team, "pagetype_name": "Release Group"}, pluck="tag")


def get_app_counts_for_groups(rg_names):
	rg_app = jingrow.qb.PageType("Release Group App")

	app_counts = (
		jingrow.qb.from_(rg_app)
		.where(rg_app.parent.isin(rg_names))
		.groupby(rg_app.parent)
		.select(
			rg_app.parent,
			jingrow.query_builder.functions.Count("*"),
		)
		.run()
	)

	app_counts_map = {}
	for rg_name, app_count in app_counts:
		app_counts_map[rg_name] = app_count

	return app_counts_map


@jingrow.whitelist()
def exists(title):
	team = get_current_team()
	return bool(jingrow.db.exists("Release Group", {"title": title, "team": team, "enabled": True}))


@jingrow.whitelist()
def get_default_apps():
	jcloud_settings = jingrow.get_single("Jcloud Settings")
	default_apps = jcloud_settings.get_default_apps()

	versions, rows = get_app_versions_list()

	version_based_default_apps = {v.version: [] for v in versions}

	for row in rows:
		if row.app in default_apps:
			version_based_default_apps[row.version].append(row)

	return version_based_default_apps


def get_app_versions_list(only_jingrow=False):
	AppSource = jingrow.qb.PageType("App Source")
	JingrowVersion = jingrow.qb.PageType("Jingrow Version")
	AppSourceVersion = jingrow.qb.PageType("App Source Version")
	rows = (
		jingrow.qb.from_(AppSourceVersion)
		.left_join(AppSource)
		.on(AppSourceVersion.parent == AppSource.name)
		.left_join(JingrowVersion)
		.on(AppSourceVersion.version == JingrowVersion.name)
		.where((AppSource.enabled == 1) & (AppSource.public == 1) & (JingrowVersion.public == 1))
		.select(
			JingrowVersion.name.as_("version"),
			JingrowVersion.status,
			JingrowVersion.default,
			AppSource.name.as_("source"),
			AppSource.app,
			AppSource.repository_url,
			AppSource.repository,
			AppSource.repository_owner,
			AppSource.branch,
			AppSource.app_title.as_("title"),
			AppSource.jingrow,
		)
		.orderby(AppSource.creation)
	)

	if only_jingrow:
		rows = rows.where(AppSource.jingrow == 1)

	rows = rows.run(as_dict=True)

	version_list = unique(rows, lambda x: x.version)

	return version_list, rows


@jingrow.whitelist()
def options():
	version_list, rows = get_app_versions_list(only_jingrow=True)
	approved_apps = jingrow.get_all("Marketplace App", filters={"jingrow_approved": 1}, pluck="app")

	versions = []
	for d in version_list:
		version_dict = {"name": d.version, "status": d.status, "default": d.default}
		version_rows = find_all(rows, lambda x: x.version == d.version)
		app_list = jingrow.utils.unique([row.app for row in version_rows])
		app_list = sorted(app_list, key=lambda x: x not in approved_apps)

		for app in app_list:
			app_rows = find_all(version_rows, lambda x: x.app == app)
			app_dict = {"name": app, "title": app_rows[0].title}

			for source in app_rows:
				source_dict = {
					"name": source.source,
					"repository_url": source.repository_url,
					"branch": source.branch,
					"repository": source.repository,
					"repository_owner": source.repository_owner,
				}
				app_dict.setdefault("sources", []).append(source_dict)

			app_dict["source"] = app_dict["sources"][0]
			version_dict.setdefault("apps", []).append(app_dict)
		versions.append(version_dict)

	clusters = Cluster.get_all_for_new_bench()

	return {"versions": versions, "clusters": clusters}


@jingrow.whitelist()
@protected("Release Group")
def bench_config(name):
	rg = jingrow.get_pg("Release Group", name)

	common_site_config = [
		{"key": config.key, "value": config.value, "type": config.type}
		for config in rg.common_site_config_table
		if not config.internal
	]

	bench_config = jingrow.parse_json(rg.bench_config)
	if bench_config.get("http_timeout"):
		bench_config = [
			jingrow._dict(
				key="http_timeout",
				value=bench_config.get("http_timeout"),
				type="Number",
				internal=False,
			)
		]
	else:
		bench_config = []

	config = common_site_config + bench_config

	secret_keys = jingrow.get_all("Site Config Key", filters={"type": "Password"}, pluck="key")
	for c in config:
		if c["key"] in secret_keys:
			c["value"] = "*******"
			c["type"] = "Password"
	return config


@jingrow.whitelist()
@protected("Release Group")
def update_config(name, config):
	sanitized_common_site_config, sanitized_bench_config = [], []
	bench_config_keys = ["http_timeout"]

	config = jingrow.parse_json(config)
	config = [jingrow._dict(c) for c in config]

	for c in config:
		if c.key in get_client_blacklisted_keys():
			continue

		if jingrow.db.exists("Site Config Key", c.key):
			c.type = jingrow.db.get_value("Site Config Key", c.key, "type")
		format_config_value(name, c)

		if c.key in bench_config_keys:
			sanitized_bench_config.append(c)
		else:
			sanitized_common_site_config.append(c)

	rg: ReleaseGroup = jingrow.get_pg("Release Group", name)
	rg.update_config_in_release_group(sanitized_common_site_config, sanitized_bench_config)
	rg.update_benches_config()
	return list(filter(lambda x: not x.internal, rg.common_site_config_table))


def format_config_value(group: str, c: jingrow._dict):
	if c.type == "Number":
		c.value = flt(c.value)
	elif c.type == "Boolean":
		c.value = bool(sbool(c.value))
	elif c.type == "JSON":
		c.value = jingrow.parse_json(c.value)
	elif c.type == "Password" and c.value == "*******":
		c.value = jingrow.get_value("Site Config", {"key": c.key, "parent": group}, "value")


@jingrow.whitelist()
@protected("Release Group")
def dependencies(name: str):
	rg: ReleaseGroup = jingrow.get_pg("Release Group", name)
	active_dependencies = [{"key": d.dependency, "value": d.version} for d in rg.dependencies]
	supported_dependencies = jingrow.db.get_all(
		"Bench Dependency Version",
		{"supported_jingrow_version": rg.version},
		["parent as `key`", "version as `value`"],
	)

	bench_dependencies = jingrow.get_all("Bench Dependency", ["name", "title", "internal"])

	return {
		"active_dependencies": active_dependencies,
		"supported_dependencies": list(
			# deduplicate dependencies
			{d["value"]: d for d in supported_dependencies + active_dependencies}.values()
		),
		"dependency_title": {d["name"]: d["title"] for d in bench_dependencies},
		"internal_dependencies": [d["name"] for d in bench_dependencies if d["internal"]],
		"update_available": rg.dependency_update_pending,
	}


@jingrow.whitelist()
@protected("Release Group")
def update_dependencies(name: str, dependencies: str):
	dependencies = jingrow.parse_json(dependencies)
	rg: ReleaseGroup = jingrow.get_pg("Release Group", name)
	if len(rg.dependencies) != len(dependencies):
		jingrow.throw("Need all required dependencies")
	if diff := set([d["key"] for d in dependencies]) - set(d.dependency for d in rg.dependencies):
		jingrow.throw("Invalid dependencies: " + ", ".join(diff))
	for dep, new in zip(
		sorted(rg.dependencies, key=lambda x: x.dependency),
		sorted(dependencies, key=lambda x: x["key"]),
	):
		if dep.dependency != new["key"]:
			jingrow.throw(f"Invalid dependency: {new['key']}")
		if not re.match(r"^\d+\.\d+\.*\d*$", new["value"]):
			jingrow.throw(f"Invalid version for {new['key']}")
		dep.version = new["value"]
	rg.save()


@jingrow.whitelist()
@protected("Release Group")
def apps(name):
	group = jingrow.get_pg("Release Group", name)
	apps = []
	deployed_apps = jingrow.db.get_all(
		"Bench",
		filters={"group": group.name, "status": ("!=", "Archived")},
		fields=["`tabBench App`.app"],
		pluck="app",
	)
	deployed_apps = unique(deployed_apps)
	updates = deploy_information(name)

	latest_bench = jingrow.get_all(
		"Bench",
		filters={"group": group.name, "status": "Active"},
		order_by="creation desc",
		limit=1,
		pluck="name",
	)
	if latest_bench:
		latest_bench = latest_bench[0]
	else:
		latest_bench = None

	latest_deployed_apps = jingrow.get_all(
		"Bench",
		filters={"name": latest_bench},
		fields=["`tabBench App`.app", "`tabBench App`.hash"],
	)

	for app in group.apps:
		source = jingrow.get_pg("App Source", app.source)
		app = jingrow.get_pg("App", app.app)
		update_available = updates["update_available"] and find(
			updates.apps, lambda x: x["app"] == app.name and x["update_available"]
		)

		latest_deployed_app = find(latest_deployed_apps, lambda x: x.app == app.name)
		hash = latest_deployed_app.hash if latest_deployed_app else None
		tag = get_app_tag(source.repository, source.repository_owner, hash)

		apps.append(
			{
				"name": app.name,
				"jingrow": app.jingrow,
				"title": app.title,
				"branch": source.branch,
				"repository_url": source.repository_url,
				"repository": source.repository,
				"repository_owner": source.repository_owner,
				"tag": tag,
				"hash": hash,
				"deployed": app.name in deployed_apps,
				"update_available": bool(update_available),
				"last_github_poll_failed": source.last_github_poll_failed,
			}
		)
	return apps


@jingrow.whitelist()
@protected("Release Group")
def installable_apps(name):
	release_group = jingrow.get_pg("Release Group", name)
	installed_apps = [app.app for app in release_group.apps]
	versions = options()["versions"]
	version = find(versions, lambda x: x["name"] == release_group.version)
	apps = version["apps"] if version else []
	return [app for app in apps if app["name"] not in installed_apps]


@jingrow.whitelist()
@protected("Release Group")
def all_apps(name):
	"""Return all apps in the marketplace that are not installed in the release group for adding new apps"""

	release_group = jingrow.get_pg("Release Group", name)
	installed_apps = [app.app for app in release_group.apps]
	marketplace_apps = jingrow.get_all(
		"Marketplace App",
		filters={"status": "Published", "app": ("not in", installed_apps)},
		fields=["name", "title", "image", "app"],
	)

	if not marketplace_apps:
		return []

	AppSource = jingrow.qb.PageType("App Source")
	AppSourceVersion = jingrow.qb.PageType("App Source Version")
	marketplace_app_sources = (
		jingrow.qb.from_(AppSource)
		.left_join(AppSourceVersion)
		.on(AppSourceVersion.parent == AppSource.name)
		.select(
			AppSource.name,
			AppSource.branch,
			AppSource.repository,
			AppSource.repository_owner,
			AppSource.app,
			AppSourceVersion.version,
		)
		.where(
			(AppSource.app.isin([app.app for app in marketplace_apps]))
			& (AppSource.enabled == 1)
			& (AppSource.public == 1)
		)
	).run(as_dict=1)

	total_installs_by_app = get_total_installs_by_app()

	for app in marketplace_apps:
		app["sources"] = find_all(
			list(filter(lambda x: x.version == release_group.version, marketplace_app_sources)),
			lambda x: x.app == app.app,
		)
		# for fetching repo details for incompatible apps
		app_source = find(marketplace_app_sources, lambda x: x.app == app.app)
		app["repo"] = f"{app_source.repository_owner}/{app_source.repository}" if app_source else None
		app["total_installs"] = total_installs_by_app.get(app["name"], 0)

	return marketplace_apps


@jingrow.whitelist()
@protected("Release Group")
def fetch_latest_app_update(name, app):
	jingrow.get_pg("Release Group", name).fetch_latest_app_update(app)


@jingrow.whitelist()
@protected("Release Group")
def add_app(name, source, app):
	add_apps(name, [{"app": app, "source": source}])


@jingrow.whitelist()
@protected("Release Group")
def add_apps(name, apps):
	release_group: "ReleaseGroup" = jingrow.get_pg("Release Group", name)
	for app in apps:
		app_name, source = app.values()
		release_group.update_source(jingrow._dict(name=source, app=app_name))


@jingrow.whitelist()
@protected("Release Group")
def remove_app(name, app):
	return jingrow.get_pg("Release Group", name).remove_app(app)


@jingrow.whitelist()
@protected("Release Group")
def versions(name):
	Bench = jingrow.qb.PageType("Bench")
	Server = jingrow.qb.PageType("Server")
	deployed_versions = (
		jingrow.qb.from_(Bench)
		.left_join(Server)
		.on(Server.name == Bench.server)
		.where((Bench.group == name) & (Bench.status != "Archived"))
		.groupby(Bench.name)
		.select(Bench.name, Bench.status, Bench.is_ssh_proxy_setup, Server.proxy_server)
		.orderby(Bench.creation, order=jingrow.qb.desc)
		.run(as_dict=True)
	)

	rg_version = jingrow.db.get_value("Release Group", name, "version")

	sites_in_group_details = jingrow.db.get_all(
		"Site",
		filters={
			"group": name,
			"status": ("not in", ("Archived", "Suspended")),
			"is_standby": 0,
		},
		fields=["name", "status", "cluster", "plan", "creation", "bench"],
	)

	if sites_in_group_details:
		Cluster = jingrow.qb.PageType("Cluster")
		cluster_data = (
			jingrow.qb.from_(Cluster)
			.select(Cluster.name, Cluster.title, Cluster.image)
			.where(Cluster.name.isin([site.cluster for site in sites_in_group_details]))
			.run(as_dict=True)
		)

		Plan = jingrow.qb.PageType("Site Plan")
		plan_data = (
			jingrow.qb.from_(Plan)
			.select(Plan.name, Plan.plan_title, Plan.price_cny, Plan.price_usd)
			.where(Plan.name.isin([site.plan for site in sites_in_group_details]))
			.run(as_dict=True)
		)

		ResourceTag = jingrow.qb.PageType("Resource Tag")
		tag_data = (
			jingrow.qb.from_(ResourceTag)
			.select(ResourceTag.tag_name, ResourceTag.parent)
			.where(ResourceTag.parent.isin([site.name for site in sites_in_group_details]))
			.run(as_dict=True)
		)
	else:
		cluster_data = plan_data = tag_data = {}

	for version in deployed_versions:
		version.sites = find_all(sites_in_group_details, lambda x: x.bench == version.name)
		version.version = rg_version
		for site in version.sites:
			site.version = rg_version
			site.server_region_info = find(cluster_data, lambda x: x.name == site.cluster)
			site.plan = find(plan_data, lambda x: x.name == site.plan)
			tags = find_all(tag_data, lambda x: x.parent == site.name)
			site.tags = [tag.tag_name for tag in tags]

		version.deployed_on = jingrow.db.get_value(
			"Agent Job",
			{"bench": version.name, "job_type": "New Bench", "status": "Success"},
			"end",
		)

	return deployed_versions


@jingrow.whitelist()
@protected("Bench")
def get_installed_apps_in_version(name):
	apps = jingrow.db.get_all(
		"Bench App",
		{"parent": name},
		["name", "app", "hash", "source"],
		order_by="idx",
	)
	for app in apps:
		app.update(
			jingrow.db.get_value(
				"App Source",
				app.source,
				("branch", "repository", "repository_owner", "repository_url"),
				as_dict=1,
				cache=True,
			)
		)
		app.tag = get_app_tag(app.repository, app.repository_owner, app.hash)

	return apps


@jingrow.whitelist()
@protected("Bench")
def get_processes(name):
	bench: "Bench" = jingrow.get_pg("Bench", name)
	if bench.status != "Active" and bench.status != "Broken":
		return []

	return bench.supervisorctl_status()


@jingrow.whitelist()
@protected("Release Group")
def candidates(filters=None, order_by=None, limit_start=None, limit_page_length=None):
	result = jingrow.get_all(
		"Deploy Candidate",
		["name", "creation", "status"],
		{"group": filters["group"], "status": ("!=", "Draft")},
		order_by=order_by or "creation desc",
		start=limit_start,
		limit=limit_page_length,
	)
	candidates = OrderedDict()
	for d in result:
		candidates.setdefault(d.name, {})
		candidates[d.name].update(d)
		dc_apps = jingrow.get_all(
			"Deploy Candidate App",
			filters={"parent": d.name},
			pluck="app",
			order_by="creation desc",
		)
		candidates[d.name]["apps"] = dc_apps

	return candidates.values()


@jingrow.whitelist()
def candidate(name):
	if not name:
		return None

	candidate = jingrow.get_pg("Deploy Candidate", name)
	jobs = []
	deploys = jingrow.get_all("Deploy", {"candidate": name}, limit=1)
	if deploys:
		deploy = jingrow.get_pg("Deploy", deploys[0].name)
		for bench in deploy.benches:
			if not bench.bench:
				continue
			job = jingrow.get_all(
				"Agent Job",
				["name", "status", "end", "duration", "bench"],
				{"bench": bench.bench, "job_type": "New Bench"},
				limit=1,
			) or [{}]
			jobs.append(job[0])

	return {
		"name": candidate.name,
		"status": candidate.status,
		"creation": candidate.creation,
		"deployed": False,
		"build_steps": candidate.build_steps,
		"build_start": candidate.build_start,
		"build_end": candidate.build_end,
		"build_duration": candidate.build_duration,
		"apps": candidate.apps,
		"jobs": jobs,
	}


@jingrow.whitelist()
@protected("Release Group")
def deploy_information(name):
	rg: ReleaseGroup = jingrow.get_pg("Release Group", name)
	return rg.deploy_information()


@jingrow.whitelist()
@protected("Release Group")
def deploy(name, apps):
	team = get_current_team(True)
	rg: ReleaseGroup = jingrow.get_pg("Release Group", name)

	if rg.team != team.name:
		jingrow.throw("Bench can only be deployed by the bench owner", exc=jingrow.PermissionError)

	if rg.deploy_in_progress:
		jingrow.throw("A deploy for this bench is already in progress")

	candidate = rg.create_deploy_candidate(apps)
	candidate.schedule_build_and_deploy()

	return candidate.name


@jingrow.whitelist()
@protected("Release Group")
def deploy_and_update(
	name: str,
	apps: list,
	sites: list | None = None,
	run_will_fail_check: bool = True,
):
	# Returns name of the Deploy Candidate that is running the build
	return get_bench_update(
		name,
		apps,
		sites,
		False,
	).deploy(run_will_fail_check)


@jingrow.whitelist()
@protected("Release Group")
def update_inplace(
	name: str,
	apps: list,
	sites: list,
):
	# Returns name of the Agent Job name that runs the inplace update
	return get_bench_update(
		name,
		apps,
		sites,
		True,
	).update_inplace()


@jingrow.whitelist()
@protected("Release Group")
def create_deploy_candidate(name, apps_to_ignore=None):
	apps_to_ignore = [] if apps_to_ignore is None else apps_to_ignore
	rg: ReleaseGroup = jingrow.get_pg("Release Group", name)
	return rg.create_deploy_candidate(apps_to_ignore)


@jingrow.whitelist()
@protected("Release Group")
def jobs(filters=None, order_by=None, limit_start=None, limit_page_length=None):
	benches = jingrow.get_all("Bench", {"group": filters["name"]}, pluck="name")
	if benches:
		jobs = jingrow.get_all(
			"Agent Job",
			fields=["name", "job_type", "creation", "status", "start", "end", "duration"],
			filters={"bench": ("in", benches)},
			order_by=order_by or "creation desc",
			start=limit_start,
			limit=limit_page_length,
			ignore_ifnull=True,
		)
		for job in jobs:
			job["status"] = "Pending" if job["status"] == "Undelivered" else job["status"]
	else:
		jobs = []
	return jobs


@jingrow.whitelist()
@protected("Release Group")
def running_jobs(name):
	benches = jingrow.get_all("Bench", {"group": name}, pluck="name")
	jobs = jingrow.get_all(
		"Agent Job",
		filters={"status": ("in", ("Pending", "Running")), "bench": ("in", benches)},
	)
	return [job_detail(job.name) for job in jobs]


@jingrow.whitelist()
@protected("Release Group")
def recent_deploys(name):
	return jingrow.get_all(
		"Deploy Candidate",
		["name", "creation"],
		{"group": name, "status": ("!=", "Draft")},
		order_by="creation desc",
		limit=3,
	)


@jingrow.whitelist()
@protected("Release Group")
def change_branch(name: str, app: str, to_branch: str):
	"""Switch to `to_branch` for `app` in release group `name`"""
	rg: ReleaseGroup = jingrow.get_pg("Release Group", name)
	rg.change_app_branch(app, to_branch)


@jingrow.whitelist()
@protected("Release Group")
def branch_list(name: str, app: str) -> list[dict]:
	"""Return a list of git branches available for the `app`"""
	rg: ReleaseGroup = jingrow.get_pg("Release Group", name)
	app_source = rg.get_app_source(app)

	installation_id = app_source.github_installation_id
	repo_owner = app_source.repository_owner
	repo_name = app_source.repository

	marketplace_app = jingrow.get_all("Marketplace App", filters={"app": app}, pluck="name", limit=1)

	if marketplace_app and app_source.public and (not belongs_to_current_team(marketplace_app[0])):
		return get_branches_for_marketplace_app(app, marketplace_app[0], app_source)

	return branches(repo_owner, repo_name, installation_id)


def get_branches_for_marketplace_app(app: str, marketplace_app: str, app_source: AppSource) -> list[dict]:
	"""Return list of branches allowed for this `marketplace` app"""
	branch_set = set()
	marketplace_app = jingrow.get_pg("Marketplace App", marketplace_app)

	for marketplace_app_source in marketplace_app.sources:
		app_source = jingrow.get_pg("App Source", marketplace_app_source.source)
		branch_set.add(app_source.branch)

	# Also, append public source branches
	repo_owner = app_source.repository_owner
	repo_name = app_source.repository

	public_app_sources = jingrow.get_all(
		"App Source",
		filters={
			"app": app,
			"repository_owner": repo_owner,
			"repository": repo_name,
			"public": True,
		},
		pluck="branch",
	)
	branch_set.update(public_app_sources)

	branch_list = sorted(list(branch_set))
	return [{"name": b} for b in branch_list]


def belongs_to_current_team(app: str) -> bool:
	"""Does the Marketplace App `app` belong to current team"""
	current_team = get_current_team()
	marketplace_app = jingrow.get_pg("Marketplace App", app)

	return marketplace_app.team == current_team


@jingrow.whitelist()
@protected("Release Group")
def regions(name):
	rg = jingrow.get_pg("Release Group", name)
	cluster_names = rg.get_clusters()
	return jingrow.get_all(
		"Cluster", fields=["name", "title", "image"], filters={"name": ("in", cluster_names)}
	)


@jingrow.whitelist()
@protected("Release Group")
def available_regions(name):
	rg = jingrow.get_pg("Release Group", name)
	cluster_names = rg.get_clusters()
	return Cluster.get_all_for_new_bench({"name": ("not in", cluster_names)})


@jingrow.whitelist()
@protected("Release Group")
def add_region(name, region):
	jingrow.get_pg("Release Group", name).add_region(region)


@jingrow.whitelist()
@protected("Release Group")
def archive(name):
	benches = jingrow.get_all("Bench", filters={"group": name, "status": "Active"}, pluck="name")

	for bench in benches:
		jingrow.get_pg("Bench", bench).archive()

	group = jingrow.get_pg("Release Group", name)
	new_name = f"{group.title}.archived"
	group.title = append_number_if_name_exists("Release Group", new_name, "title", separator=".")
	group.enabled = 0
	group.save()


@jingrow.whitelist()
@protected("Bench")
def restart(name):
	jingrow.get_pg("Bench", name).restart()


@jingrow.whitelist()
@protected("Bench")
def rebuild(name):
	jingrow.get_pg("Bench", name).rebuild()


@jingrow.whitelist()
@protected("Bench")
def update(name):
	jingrow.get_pg("Bench", name).update_all_sites()


@jingrow.whitelist()
@protected("Release Group")
def update_all_sites(name):
	benches = jingrow.get_all("Bench", {"group": name, "status": "Active"})
	for bench in benches:
		jingrow.get_cached_pg("Bench", bench).update_all_sites()


@jingrow.whitelist()
@protected("Release Group")
def logs(name, bench):
	from jcloud.agent import AgentRequestSkippedException

	if jingrow.db.get_value("Bench", bench, "group") != name:
		return []

	try:
		return jingrow.get_pg("Bench", bench).server_logs
	except AgentRequestSkippedException:
		return []


@jingrow.whitelist()
@protected("Release Group")
def log(name, bench, log):
	if jingrow.db.get_value("Bench", bench, "group") != name:
		jingrow.throw(f"Release Group name {name} does not match Bench Release Group")
	return jingrow.get_pg("Bench", bench).get_server_log(log)


@jingrow.whitelist()
@protected("Release Group")
def certificate(name):
	return jingrow.get_pg("Release Group", name).get_certificate()


@jingrow.whitelist()
@protected("Release Group")
def generate_certificate(name):
	return jingrow.get_pg("Release Group", name).generate_certificate()


@jingrow.whitelist()
@protected("Release Group")
def get_title_and_creation(name):
	result = jingrow.db.get_value("Release Group", name, ["title", "creation"], as_dict=True)
	server = jingrow.get_all(
		"Release Group Server", {"parent": name}, pluck="server", order_by="idx asc", limit=1
	)[0]
	result["team"] = jingrow.db.get_value("Server", server, "team")
	return result


@jingrow.whitelist()
@protected("Release Group")
def rename(name, title):
	return jingrow.db.set_value("Release Group", name, "title", title)


@jingrow.whitelist()
@protected("Release Group")
def apply_patch(release_group: str, app: str, patch_config: dict) -> list[str]:
	team = get_current_team()

	return create_app_patch(
		release_group,
		app,
		team,
		patch_config,
	)


@jingrow.whitelist()
@protected("Release Group")
def fail_and_redeploy(name: str, dc_name: str):
	dc: "DeployCandidate" = jingrow.get_pg("Deploy Candidate", dc_name)
	res = dc.fail_and_redeploy()

	# If failed error is True
	if res.get("error"):
		return None

	# New Deploy Candidate name
	return res.get("message")


@jingrow.whitelist(allow_guest=True)
def confirm_bench_transfer(key: str):
	from jingrow import _

	if jingrow.session.user == "Guest":
		return jingrow.respond_as_web_page(
			_("Not Permitted"),
			_("You need to be logged in to confirm the bench group transfer."),
			http_status_code=403,
			indicator_color="red",
			primary_action="/dashboard/login",
			primary_label=_("Login"),
		)

	if not isinstance(key, str):
		return jingrow.respond_as_web_page(
			_("Not Permitted"),
			_("The link you are using is invalid."),
			http_status_code=403,
			indicator_color="red",
		)

	if team_change := jingrow.db.get_value("Team Change", {"key": key}):
		team_change = jingrow.get_pg("Team Change", team_change)
		to_team = team_change.to_team
		if not jingrow.db.get_value(
			"Team Member", {"user": jingrow.session.user, "parent": to_team, "parenttype": "Team"}
		):
			return jingrow.respond_as_web_page(
				_("Not Permitted"),
				_("You are not a member of the team to which the site is being transferred."),
				http_status_code=403,
				indicator_color="red",
			)

		team_change.transfer_completed = True
		team_change.save()
		jingrow.db.commit()

		jingrow.response.type = "redirect"
		jingrow.response.location = f"/dashboard/groups/{team_change.document_name}"
		return None

	return jingrow.respond_as_web_page(
		_("Not Permitted"),
		_("The link you are using is invalid or expired."),
		http_status_code=403,
		indicator_color="red",
	)
