# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt


import click
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_fields
from frappe.desk.page.setup_wizard.setup_wizard import add_all_roles_to

import erpnext
from erpnext.setup.default_energy_point_rules import get_default_energy_point_rules
from erpnext.setup.doctype.incoterm.incoterm import create_incoterms
from erpnext.setup.utils import identity as _

from .default_success_action import get_default_success_action

default_mail_footer = """<div style="padding: 7px; text-align: right; color: #888"><small>Sent via
	<a style="color: #888" href="http://frappe.io/erpnext">ERPNext</a></div>"""


def after_install():
	if not frappe.db.exists("Role", "Analytics"):
		frappe.get_doc({"doctype": "Role", "role_name": "Analytics"}).insert()

	set_single_defaults()
	create_print_setting_custom_fields()
	create_address_and_contact_custom_fields()
	create_custom_company_links()
	add_all_roles_to("Administrator")
	create_default_success_action()
	create_default_energy_point_rules()
	create_incoterms()
	create_default_role_profiles()
	add_company_to_session_defaults()
	add_standard_navbar_items()
	grant_address_read_to_accounts_manager()
	add_app_name()
	hide_workspaces()
	update_roles()
	update_pegged_currencies()
	frappe.db.commit()


def check_frappe_version():
	def major_version(v: str) -> str:
		return v.split(".")[0]

	frappe_version = major_version(frappe.__version__)
	erpnext_version = major_version(erpnext.__version__)

	if frappe_version == erpnext_version:
		return

	click.secho(
		f"You're attempting to install ERPNext version {erpnext_version} with Frappe version {frappe_version}. "
		"This is not supported and will result in broken install. Switch to correct branch before installing.",
		fg="red",
	)

	raise SystemExit(1)


def set_single_defaults():
	for dt in (
		"Accounts Settings",
		"Print Settings",
		"Buying Settings",
		"Selling Settings",
		"Stock Settings",
	):
		default_values = frappe.db.sql(
			"""select fieldname, `default` from `tabDocField`
			where parent=%s""",
			dt,
		)
		if default_values:
			try:
				doc = frappe.get_doc(dt, dt)
				for fieldname, value in default_values:
					doc.set(fieldname, value)
				doc.flags.ignore_mandatory = True
				doc.save()
			except frappe.ValidationError:
				pass

	frappe.db.set_default("date_format", "dd-mm-yyyy")

	setup_currency_exchange()


def setup_currency_exchange():
	ces = frappe.get_single("Currency Exchange Settings")
	try:
		ces.service_provider = "frankfurter.dev - v2"
		ces.save()
	except frappe.ValidationError:
		pass


def create_print_setting_custom_fields():
	create_custom_fields(
		{
			"Print Settings": [
				{
					"label": _("Compact Item Print"),
					"fieldname": "compact_item_print",
					"fieldtype": "Check",
					"default": "1",
					"insert_after": "with_letterhead",
				},
				{
					"label": _("Print UOM after Quantity"),
					"fieldname": "print_uom_after_quantity",
					"fieldtype": "Check",
					"default": "0",
					"insert_after": "compact_item_print",
				},
				{
					"label": _("Print taxes with zero amount"),
					"fieldname": "print_taxes_with_zero_amount",
					"fieldtype": "Check",
					"default": "0",
					"insert_after": "allow_print_for_cancelled",
				},
			]
		}
	)


def create_address_and_contact_custom_fields():
	create_custom_fields(
		{
			"Address": [
				{
					"label": _("Tax Category"),
					"fieldname": "tax_category",
					"fieldtype": "Link",
					"options": "Tax Category",
					"insert_after": "fax",
				},
				{
					"label": _("Is Your Company Address"),
					"fieldname": "is_your_company_address",
					"fieldtype": "Check",
					"default": "0",
					"insert_after": "linked_with",
				},
			],
			"Contact": [
				{
					"label": _("Is Billing Contact"),
					"fieldname": "is_billing_contact",
					"fieldtype": "Check",
					"insert_after": "is_primary_contact",
				},
			],
		}
	)


def create_custom_company_links():
	"""Add link fields to Company in Email Account and Communication.

	These DocTypes are provided by the Frappe Framework but need to be associated
	with a company in ERPNext to allow for multitenancy. I.e. one company should
	not be able to access emails and communications from another company.
	"""
	create_custom_fields(
		{
			"Email Account": [
				{
					"label": _("Company"),
					"fieldname": "company",
					"fieldtype": "Link",
					"options": "Company",
					"insert_after": "email_id",
				},
			],
			"Communication": [
				{
					"label": _("Company"),
					"fieldname": "company",
					"fieldtype": "Link",
					"options": "Company",
					"insert_after": "email_account",
					"fetch_from": "email_account.company",
					"read_only": 1,
				},
			],
		},
	)


def create_default_success_action():
	for success_action in get_default_success_action():
		if not frappe.db.exists("Success Action", success_action.get("ref_doctype")):
			doc = frappe.get_doc(success_action)
			doc.insert(ignore_permissions=True)


def create_default_energy_point_rules():
	for rule in get_default_energy_point_rules():
		# check if any rule for ref. doctype exists
		rule_exists = frappe.db.exists(
			"Energy Point Rule", {"reference_doctype": rule.get("reference_doctype")}
		)
		if rule_exists:
			continue
		doc = frappe.get_doc(rule)
		doc.insert(ignore_permissions=True)


def add_company_to_session_defaults():
	settings = frappe.get_single("Session Default Settings")
	settings.append("session_defaults", {"ref_doctype": "Company"})
	settings.save()


def add_standard_navbar_items():
	navbar_settings = frappe.get_single("Navbar Settings")
	erpnext_navbar_items = [
		{
			"item_label": _("Documentation"),
			"item_type": "Route",
			"route": "https://docs.erpnext.com/",
			"is_standard": 1,
		},
		{
			"item_label": _("User Forum"),
			"item_type": "Route",
			"route": "https://discuss.frappe.io",
			"is_standard": 1,
		},
		{
			"item_label": _("Frappe School"),
			"item_type": "Route",
			"route": "https://frappe.io/school?utm_source=in_app",
			"is_standard": 1,
		},
		{
			"item_label": _("Report an Issue"),
			"item_type": "Route",
			"route": "https://github.com/frappe/erpnext/issues",
			"is_standard": 1,
		},
	]

	current_navbar_items = navbar_settings.help_dropdown
	navbar_settings.set("help_dropdown", [])

	for item in erpnext_navbar_items:
		current_labels = [item.get("item_label") for item in current_navbar_items]
		if item.get("item_label") not in current_labels:
			navbar_settings.append("help_dropdown", item)

	for item in current_navbar_items:
		navbar_settings.append(
			"help_dropdown",
			{
				"item_label": item.item_label,
				"item_type": item.item_type,
				"route": item.route,
				"action": item.action,
				"is_standard": item.is_standard,
				"hidden": item.hidden,
			},
		)

	navbar_settings.save()


def add_app_name():
	frappe.db.set_single_value("System Settings", "app_name", "ERPNext")


def hide_workspaces():
	for ws in ["Integration", "Settings"]:
		frappe.db.set_value("Workspace", ws, "public", 0)


def update_roles():
	website_user_roles = ("Customer", "Supplier")
	for role in website_user_roles:
		frappe.db.set_value("Role", role, "desk_access", 0)


def create_default_role_profiles():
	for role_profile_name, roles in DEFAULT_ROLE_PROFILES.items():
		if frappe.db.exists("Role Profile", role_profile_name):
			role_profile = frappe.get_doc("Role Profile", role_profile_name)
			existing_roles = [row.role for row in role_profile.roles]

			role_profile.roles = [row for row in role_profile.roles if row.role in roles]

			for role in roles:
				if role not in existing_roles:
					role_profile.append("roles", {"role": role})

			role_profile.save(ignore_permissions=True)

			continue

		role_profile = frappe.new_doc("Role Profile")
		role_profile.role_profile = role_profile_name
		for role in roles:
			role_profile.append("roles", {"role": role})

		role_profile.insert(ignore_permissions=True)


def update_pegged_currencies():
	doc = frappe.get_doc("Pegged Currencies", "Pegged Currencies")

	existing_sources = {item.source_currency for item in doc.pegged_currency_item}

	currencies_to_add = [
		{"source_currency": "AED", "pegged_against": "USD", "pegged_exchange_rate": 3.6725},
		{"source_currency": "BHD", "pegged_against": "USD", "pegged_exchange_rate": 0.376},
		{"source_currency": "JOD", "pegged_against": "USD", "pegged_exchange_rate": 0.709},
		{"source_currency": "OMR", "pegged_against": "USD", "pegged_exchange_rate": 0.3845},
		{"source_currency": "QAR", "pegged_against": "USD", "pegged_exchange_rate": 3.64},
		{"source_currency": "SAR", "pegged_against": "USD", "pegged_exchange_rate": 3.75},
	]

	# Add items on pegged_currency_item if source_currency and pegged_against currency doc exist.

	currencies_exist = frappe.db.get_list(
		"Currency", {"name": ["in", ["AED", "BHD", "JOD", "OMR", "QAR", "SAR", "USD"]]}, pluck="name"
	)

	if "USD" not in currencies_exist:
		return

	for currency in currencies_to_add:
		if (
			currency["source_currency"] in currencies_exist
			and currency["source_currency"] not in existing_sources
		):
			doc.append("pegged_currency_item", currency)

	doc.save()


DEFAULT_ROLE_PROFILES = {
	"Inventory": [
		"Stock User",
		"Stock Manager",
		"Item Manager",
	],
	"Manufacturing": [
		"Stock User",
		"Manufacturing User",
		"Manufacturing Manager",
	],
	"Accounts": [
		"Accounts User",
		"Accounts Manager",
	],
	"Sales": [
		"Sales User",
		"Stock User",
		"Sales Manager",
	],
	"Purchase": [
		"Item Manager",
		"Stock User",
		"Purchase User",
		"Purchase Manager",
	],
}


def after_app_install(app_name=None):
	if app_name == "crm":
		from erpnext.crm.frappe_crm_api import remove_allowed_users_on_crm_install

		remove_allowed_users_on_crm_install()


def after_app_uninstall(app_name=None):
	if app_name == "crm":
		from erpnext.crm.frappe_crm_api import disable_frappe_crm_data_synchronization_on_crm_uninstall

		disable_frappe_crm_data_synchronization_on_crm_uninstall()

		frappe.db.commit()  # nosemgrep


def grant_address_read_to_accounts_manager():
	from frappe.permissions import add_permission, get_all_perms, update_permission_property

	if not frappe.db.exists("Role", "Accounts Manager"):
		return
	for rule in get_all_perms("Accounts Manager"):
		if rule.parent == "Address":
			print("Address / Accounts Manager: kept, the site already has a rule")
			return
	try:
		frappe.db.savepoint("grant_address_read_to_accounts_manager")
		add_permission("Address", "Accounts Manager", 0, "read")
		update_permission_property("Address", "Accounts Manager", 0, "export", 0)
		frappe.clear_cache(doctype="Address")
		print("Address / Accounts Manager: added read")
	except Exception:
		frappe.db.rollback(save_point="grant_address_read_to_accounts_manager")
		frappe.log_error(
			title="Could not add permission",
			message=f"Address / Accounts Manager\n\n{frappe.get_traceback()}",
		)
