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

import jingrow

from jcloud.jcloud.pagetype.site_plan.plan import Plan

UNLIMITED_PLANS = ["Unlimited", "Unlimited - Supported"]


class SitePlan(Plan):
	# begin: auto-generated types
	# This code is auto-generated. Do not modify anything in this block.

	from typing import TYPE_CHECKING

	if TYPE_CHECKING:
		from jcloud.jcloud.pagetype.site_plan_allowed_app.site_plan_allowed_app import SitePlanAllowedApp
		from jcloud.jcloud.pagetype.site_plan_release_group.site_plan_release_group import SitePlanReleaseGroup
		from jingrow.core.pagetype.has_role.has_role import HasRole
		from jingrow.types import DF

		allow_downgrading_from_other_plan: DF.Check
		allowed_apps: DF.Table[SitePlanAllowedApp]
		cluster: DF.Link | None
		cpu_time_per_day: DF.Float
		database_access: DF.Check
		dedicated_server_plan: DF.Check
		disk: DF.Int
		document_type: DF.Link
		enabled: DF.Check
		instance_type: DF.Data | None
		interval: DF.Literal["Daily", "Monthly", "Annually"]
		is_jingrow_plan: DF.Check
		is_trial_plan: DF.Check
		max_database_usage: DF.Int
		max_storage_usage: DF.Int
		memory: DF.Int
		monitor_access: DF.Check
		offsite_backups: DF.Check
		plan_level: DF.Literal["1", "2", "3", "4", "5"]
		plan_title: DF.Data | None
		price_cny: DF.Currency
		price_usd: DF.Currency
		private_benches: DF.Check
		release_groups: DF.Table[SitePlanReleaseGroup]
		roles: DF.Table[HasRole]
		support_included: DF.Check
		vcpu: DF.Int
	# end: auto-generated types

	dashboard_fields = (
		"name",
		"plan_title",
		"plan_level",
		"interval",
		"document_type",
		"document_name",
		"price_cny",
		"price_usd",
		"period",
		"cpu_time_per_day",
		"max_database_usage",
		"max_storage_usage",
		"database_access",
		"support_included",
		"private_benches",
		"monitor_access",
		"is_trial_plan",
	)

	def get_pg(self, pg):
		pg["price_per_day_cny"] = self.get_price_per_day("CNY")
		pg["price_per_day_usd"] = self.get_price_per_day("USD")
		return pg

	@classmethod
	def get_ones_without_offsite_backups(cls) -> list[str]:
		return jingrow.get_all("Site Plan", filters={"offsite_backups": False}, pluck="name")


def get_plan_config(name):
	limits = jingrow.db.get_value(
		"Site Plan",
		name,
		["cpu_time_per_day", "max_database_usage", "max_storage_usage"],
		as_dict=True,
	)
	if limits and limits.get("cpu_time_per_day", 0) > 0:
		return {
			"rate_limit": {"limit": limits.cpu_time_per_day * 3600, "window": 86400},
			"plan_limit": {
				"max_database_usage": limits.max_database_usage,
				"max_storage_usage": limits.max_storage_usage,
			},
		}
	return {}
