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

import json

import jingrow
from jingrow import _
from jingrow.geo.country_info import get_country_info
from jingrow.permissions import AUTOMATIC_ROLES
from jingrow.translate import send_translations, set_default_language
from jingrow.utils import cint, now, strip
from jingrow.utils.password import update_password
from jingrow.cache_manager import clear_defaults_cache

from . import install_fixtures


def get_setup_stages(args):  # nosemgrep
	# App setup stage functions should not include jingrow.db.commit
	# That is done by jingrow after successful completion of all stages
	stages = [
		{
			"status": _("Updating global settings"),
			"fail_msg": _("Failed to update global settings"),
			"tasks": [
				{"fn": update_global_settings, "args": args, "fail_msg": "Failed to update global settings"}
			],
		}
	]

	stages += get_stages_hooks(args) + get_setup_complete_hooks(args)

	stages.append(
		{
			# post executing hooks
			"status": _("Wrapping up"),
			"fail_msg": _("Failed to complete setup"),
			"tasks": [{"fn": run_post_setup_complete, "args": args, "fail_msg": "Failed to complete setup"}],
		}
	)

	return stages


@jingrow.whitelist()
def setup_complete(args):
	"""Calls hooks for `setup_wizard_complete`, sets home page as `desktop`
	and clears cache. If wizard breaks, calls `setup_wizard_exception` hook"""

	# Setup complete: do not throw an exception, let the user continue to desk
	if cint(jingrow.db.get_single_value("System Settings", "setup_complete")):
		return {"status": "ok"}

	args = parse_args(sanitize_input(args))
	stages = get_setup_stages(args)
	is_background_task = jingrow.conf.get("trigger_site_setup_in_background")

	if is_background_task:
		process_setup_stages.enqueue(stages=stages, user_input=args, is_background_task=True)
		return {"status": "registered"}
	else:
		return process_setup_stages(stages, args)


@jingrow.task()
def process_setup_stages(stages, user_input, is_background_task=False):
	from jingrow.utils.telemetry import capture

	capture("initated_server_side", "setup")
	try:
		jingrow.flags.in_setup_wizard = True
		current_task = None
		for idx, stage in enumerate(stages):
			jingrow.publish_realtime(
				"setup_task",
				{"progress": [idx, len(stages)], "stage_status": stage.get("status")},
				user=jingrow.session.user,
			)

			for task in stage.get("tasks"):
				current_task = task
				task.get("fn")(task.get("args"))
	except Exception:
		handle_setup_exception(user_input)
		message = current_task.get("fail_msg") if current_task else "Failed to complete setup"
		jingrow.log_error(title=f"Setup failed: {message}")
		if not is_background_task:
			jingrow.response["setup_wizard_failure_message"] = message
			raise
		jingrow.publish_realtime(
			"setup_task",
			{"status": "fail", "fail_msg": message},
			user=jingrow.session.user,
		)
	else:
		run_setup_success(user_input)
		capture("completed_server_side", "setup")
		if not is_background_task:
			return {"status": "ok"}
		jingrow.publish_realtime("setup_task", {"status": "ok"}, user=jingrow.session.user)
	finally:
		jingrow.flags.in_setup_wizard = False


def update_global_settings(args):  # nosemgrep
	if args.language and args.language != "English":
		set_default_language(get_language_code(args.lang))
		jingrow.db.commit()
	jingrow.clear_cache()

	update_system_settings(args)
	create_or_update_user(args)
	set_timezone(args)


def run_post_setup_complete(args):  # nosemgrep
	disable_future_access()
	jingrow.db.commit()
	jingrow.clear_cache()
	jingrow.clear_cache("System Settings")
	jingrow.clear_cache("System Settings", "System Settings")
	clear_defaults_cache()
	jingrow.get_cached_pg("System Settings") and jingrow.get_pg("System Settings")


def run_setup_success(args):  # nosemgrep
	for hook in jingrow.get_hooks("setup_wizard_success"):
		jingrow.get_attr(hook)(args)
	install_fixtures.install()


def get_stages_hooks(args):  # nosemgrep
	stages = []
	for method in jingrow.get_hooks("setup_wizard_stages"):
		stages += jingrow.get_attr(method)(args)
	return stages


def get_setup_complete_hooks(args):  # nosemgrep
	return [
		{
			"status": "Executing method",
			"fail_msg": "Failed to execute method",
			"tasks": [
				{
					"fn": jingrow.get_attr(method),
					"args": args,
					"fail_msg": "Failed to execute method",
				}
			],
		}
		for method in jingrow.get_hooks("setup_wizard_complete")
	]


def handle_setup_exception(args):  # nosemgrep
	jingrow.db.rollback()
	if args:
		traceback = jingrow.get_traceback(with_context=True)
		print(traceback)
		for hook in jingrow.get_hooks("setup_wizard_exception"):
			jingrow.get_attr(hook)(traceback, args)


def update_system_settings(args):  # nosemgrep
	number_format = get_country_info(args.get("country")).get("number_format", "#,###.##")

	# replace these as float number formats, as they have 0 precision
	# and are currency number formats and not for floats
	if number_format == "#.###":
		number_format = "#.###,##"
	elif number_format == "#,###":
		number_format = "#,###.##"

	system_settings = jingrow.get_pg("System Settings", "System Settings")
	system_settings.update(
		{
			"country": args.get("country"),
			"language": get_language_code(args.get("language")) or "en",
			"time_zone": args.get("timezone"),
			"currency": args.get("currency"),
			"float_precision": 3,
			"rounding_method": "Banker's Rounding",
			"date_format": jingrow.db.get_value("Country", args.get("country"), "date_format"),
			"time_format": jingrow.db.get_value("Country", args.get("country"), "time_format"),
			"number_format": number_format,
			"enable_scheduler": 1 if not jingrow.flags.in_test else 0,
			"backup_limit": 3,  # Default for downloadable backups
			"enable_telemetry": cint(args.get("enable_telemetry")),
		}
	)
	system_settings.save()
	if args.get("enable_telemetry"):
		jingrow.db.set_default("session_recording_start", now())


def create_or_update_user(args):  # nosemgrep
	try:
		email = args.get("email")
		username = args.get("username", "")
		if not username:
			return

		first_name, last_name = username, ""
		if " " in username:
			first_name, last_name = username.split(" ", 1)

		# 检查是否已存在同名用户（使用username作为唯一标识符）
		if jingrow.db.exists("User", username):
			# 更新现有用户信息
			user = jingrow.get_pg("User", username)
			user.update({
				"email": email,
				"first_name": first_name,
				"last_name": last_name,
				"full_name": username,
				"restrict_ip": "",  # 确保设置 restrict_ip 字段
				"enabled": 1  # 确保用户被启用
			})
			user.save(ignore_permissions=True)
			jingrow.db.commit()
		else:
			# 检查邮箱是否已被其他用户使用
			existing_user = jingrow.db.get_value("User", {"email": email}, "name")
			if existing_user and existing_user != username:
				raise jingrow.ValidationError(f"邮箱 {email} 已被其他用户使用")

			# 创建新用户
			_mute_emails, jingrow.flags.mute_emails = jingrow.flags.mute_emails, True
			try:
				user = jingrow.new_pg("User")
				user.update({
					"name": username,  # 使用username作为name字段
					"email": email,
					"first_name": first_name,
					"last_name": last_name,
					"full_name": username,
					"username": username,  # 确保username字段也设置
					"restrict_ip": "",  # 确保设置 restrict_ip 字段
					"enabled": 1,  # 确保用户被启用
					"user_type": "System User"  # 设置用户类型
				})
				user.append_roles(*_get_default_roles())
				user.append_roles("System Manager")
				user.flags.no_welcome_mail = True
				user.insert()
				jingrow.db.commit()
			except Exception as e:
				raise
			finally:
				jingrow.flags.mute_emails = _mute_emails

		# 更新密码
		if args.get("password"):
			try:
				update_password(username, args.get("password"))
				jingrow.db.commit()
			except Exception as e:
				raise

	except Exception as e:
		raise


def set_timezone(args):  # nosemgrep
	if args.get("timezone"):
		for name in jingrow.STANDARD_USERS:
			jingrow.db.set_value("User", name, "time_zone", args.get("timezone"))


def parse_args(args):  # nosemgrep
	if not args:
		args = jingrow.local.form_dict
	if isinstance(args, str):
		args = json.loads(args)

	args = jingrow._dict(args)

	# strip the whitespace
	for key, value in args.items():
		if isinstance(value, str):
			args[key] = strip(value)

	return args


def sanitize_input(args):
	from jingrow.utils import is_html, strip_html_tags

	if isinstance(args, str):
		args = json.loads(args)

	for key, value in args.items():
		if is_html(value):
			args[key] = strip_html_tags(value)

	return args


def add_all_roles_to(name):
	user = jingrow.get_pg("User", name)
	user.append_roles(*_get_default_roles())
	user.save()


def _get_default_roles() -> set[str]:
	skip_roles = {
		"Administrator",
		"Customer",
		"Supplier",
		"Partner",
		"Employee",
	}.union(AUTOMATIC_ROLES)
	return set(jingrow.get_all("Role", pluck="name")) - skip_roles


def disable_future_access():
	jingrow.db.set_default("desktop:home_page", "workspace")
	jingrow.db.set_single_value("System Settings", "enable_onboarding", 1)
	jingrow.db.set_single_value("System Settings", "setup_complete", 1)


@jingrow.whitelist()
def load_messages(language):
	"""Load translation messages for given language from all `setup_wizard_requires`
	javascript files"""
	from jingrow.translate import get_messages_for_boot

	jingrow.clear_cache()
	set_default_language(get_language_code(language))
	jingrow.db.commit()
	send_translations(get_messages_for_boot())
	return jingrow.local.lang


@jingrow.whitelist()
def load_languages():
	language_codes = jingrow.db.sql(
		"select language_code, language_name from tabLanguage order by name", as_dict=True
	)
	codes_to_names = {}
	for d in language_codes:
		codes_to_names[d.language_code] = d.language_name
	return {
		"default_language": jingrow.db.get_value("Language", jingrow.local.lang, "language_name")
		or jingrow.local.lang,
		"languages": sorted(jingrow.db.sql_list("select language_name from tabLanguage order by name")),
		"codes_to_names": codes_to_names,
	}


@jingrow.whitelist()
def load_country():
	from jingrow.sessions import get_geo_ip_country

	return get_geo_ip_country(jingrow.local.request_ip) if jingrow.local.request_ip else None


@jingrow.whitelist()
def get_setup_wizard_slides():
	"""Get setup wizard slides from all installed apps via hooks.
	
	Each app can define `setup_wizard_slides` in hooks.py pointing to a function
	that returns a list of slide configurations.
	
	Returns:
		list: List of slide configurations with fields definition
	"""
	slides = []
	
	# Get slides from all apps via hook
	for method in jingrow.get_hooks("setup_wizard_slides") or []:
		try:
			app_slides = jingrow.get_attr(method)()
			if app_slides:
				# Ensure app_slides is a list
				if isinstance(app_slides, dict):
					app_slides = [app_slides]
				slides.extend(app_slides)
		except Exception as e:
			jingrow.log_error(f"Failed to load setup wizard slides from {method}: {e}")
	
	return slides


@jingrow.whitelist()
def load_user_details():
	return {
		"username": jingrow.cache.hget("full_name", "signup"),
		"email": jingrow.cache.hget("email", "signup"),
	}


def prettify_args(args):  # nosemgrep
	# remove attachments
	for key, val in args.items():
		if isinstance(val, str) and "data:image" in val:
			filename = val.split("data:image", 1)[0].strip(", ")
			size = round((len(val) * 3 / 4) / 1048576.0, 2)
			args[key] = f"Image Attached: '{filename}' of size {size} MB"

	pretty_args = []
	pretty_args.extend(f"{key} = {args[key]}" for key in sorted(args))
	return pretty_args


def email_setup_wizard_exception(traceback, args):  # nosemgrep
	if not jingrow.conf.setup_wizard_exception_email:
		return

	pretty_args = prettify_args(args)
	message = """

#### Traceback

<pre>{traceback}</pre>

---

#### Setup Wizard Arguments

<pre>{args}</pre>

---

#### Request Headers

<pre>{headers}</pre>

---

#### Basic Information

- **Site:** {site}
- **User:** {user}""".format(
		site=jingrow.local.site,
		traceback=traceback,
		args="\n".join(pretty_args),
		user=jingrow.session.user,
		headers=jingrow.request.headers if jingrow.request else "[no request]",
	)

	jingrow.sendmail(
		recipients=jingrow.conf.setup_wizard_exception_email,
		sender=jingrow.session.user,
		subject=f"Setup failed: {jingrow.local.site}",
		message=message,
		delayed=False,
	)


def log_setup_wizard_exception(traceback, args):  # nosemgrep
	with open("../logs/setup-wizard.log", "w+") as setup_log:
		setup_log.write(traceback)
		setup_log.write(json.dumps(args))


def get_language_code(lang):
	return jingrow.db.get_value("Language", {"language_name": lang})


def enable_twofactor_all_roles():
	all_role = jingrow.get_pg("Role", {"role_name": "All"})
	all_role.two_factor_auth = True
	all_role.save(ignore_permissions=True)


def make_records(records, debug=False):
	from jingrow import _dict
	from jingrow.modules import scrub

	if debug:
		print("make_records: in DEBUG mode")

	# LOG every success and failure
	for record in records:
		pagetype = record.get("pagetype")
		condition = record.get("__condition")

		if condition and not condition():
			continue

		pg = jingrow.new_pg(pagetype)
		pg.update(record)

		# ignore mandatory for root
		parent_link_field = "parent_" + scrub(pg.pagetype)
		if pg.meta.get_field(parent_link_field) and not pg.get(parent_link_field):
			pg.flags.ignore_mandatory = True

		savepoint = "setup_fixtures_creation"
		try:
			jingrow.db.savepoint(savepoint)
			pg.insert(ignore_permissions=True, ignore_if_duplicate=True)
		except Exception as e:
			jingrow.clear_last_message()
			jingrow.db.rollback(save_point=savepoint)
			exception = record.get("__exception")
			if exception:
				config = _dict(exception)
				if isinstance(e, config.exception):
					config.handler()
				else:
					show_document_insert_error()
			else:
				show_document_insert_error()


def show_document_insert_error():
	print("Page Insert Error")
	print(jingrow.get_traceback())
	jingrow.log_error("Exception during Setup")
