"""Idempotent setup of an 'Employees' /desk icon under the Frappe HR folder.

HRMS v16 dropped the old 'Employee Lifecycle' workspace (see
hrms/patches/v16_0/delete_old_workspaces.py), which removed its desktop
icon from the Frappe HR folder on /desk. This re-adds it as a
jey_theme-managed record so HRMS upgrades stay untouched.

Two records are kept in sync:

1. Workspace Sidebar 'Employees' (app=hrms) — first item is a DocType
   link to Employee, which get_route_for_icon picks up on icon click
   and routes straight to /app/employee. The sidebar's app is 'hrms'
   (not 'jey_theme') so the sidebar header subtitle resolves to the
   HRMS app_title via choose_app_name in sidebar.js, not 'Jey Theme'.

2. Desktop Icon 'Employees' under parent_icon='Frappe HR' — link_type
   is 'Workspace Sidebar' (External wouldn't satisfy
   DesktopIcon.is_permitted, which requires a sidebar named after the
   icon's label or filters it out of bootinfo).

A previous version of this module also created a Workspace named
'Employees'; _cleanup_obsolete_workspace removes it on every run so
older deployments converge.
"""

import frappe

DESKTOP_ICON_LABEL = "Employees"
DESKTOP_ICON_PARENT = "Frappe HR"
DESKTOP_ICON_ICON = "users"
DESKTOP_ICON_IDX = 0

SIDEBAR_NAME = "Employees"
TARGET_DOCTYPE = "Employee"


def _cleanup_obsolete_workspace() -> str | None:
	"""Remove the 'Employees' Workspace if it was created by an earlier
	revision of this module. Sidebar + Desktop Icon are recreated below."""
	if not frappe.db.exists("Workspace", "Employees"):
		return None
	if frappe.db.get_value("Workspace", "Employees", "app") != "hrms":
		return None
	# Only delete if it's our doing — module=HR + app=hrms + the single
	# Employee link we used to create. Don't touch HRMS-shipped workspaces.
	frappe.delete_doc("Workspace", "Employees", ignore_permissions=True, force=1)
	return "deleted obsolete Workspace 'Employees'"


def ensure_workspace_sidebar() -> str:
	item = {
		"type": "Link",
		"label": TARGET_DOCTYPE,
		"link_type": "DocType",
		"link_to": TARGET_DOCTYPE,
		"icon": DESKTOP_ICON_ICON,
	}

	if frappe.db.exists("Workspace Sidebar", SIDEBAR_NAME):
		sb = frappe.get_doc("Workspace Sidebar", SIDEBAR_NAME)
		sb.title = SIDEBAR_NAME
		sb.module = "HR"
		sb.header_icon = DESKTOP_ICON_ICON
		sb.app = "hrms"
		sb.standard = 1
		sb.items = []
		sb.append("items", item)
		sb.save(ignore_permissions=True)
		return f"updated Workspace Sidebar {SIDEBAR_NAME!r}"

	sb = frappe.get_doc({
		"doctype": "Workspace Sidebar",
		"name": SIDEBAR_NAME,
		"title": SIDEBAR_NAME,
		"module": "HR",
		"header_icon": DESKTOP_ICON_ICON,
		"app": "hrms",
		"standard": 1,
		"items": [item],
	})
	sb.insert(ignore_permissions=True)
	return f"created Workspace Sidebar {SIDEBAR_NAME!r}"


def ensure_desktop_icon() -> str:
	existing = frappe.db.exists("Desktop Icon", {"label": DESKTOP_ICON_LABEL})
	if existing:
		icon = frappe.get_doc("Desktop Icon", existing)
		icon.icon = DESKTOP_ICON_ICON
		icon.icon_type = "Link"
		icon.link_type = "Workspace Sidebar"
		icon.link_to = SIDEBAR_NAME
		icon.link = None
		icon.parent_icon = DESKTOP_ICON_PARENT
		icon.app = "jey_theme"
		icon.standard = 1
		icon.hidden = 0
		icon.idx = DESKTOP_ICON_IDX
		icon.save(ignore_permissions=True)
		return f"updated Desktop Icon {DESKTOP_ICON_LABEL!r}"

	icon = frappe.get_doc({
		"doctype": "Desktop Icon",
		"label": DESKTOP_ICON_LABEL,
		"icon": DESKTOP_ICON_ICON,
		"icon_type": "Link",
		"link_type": "Workspace Sidebar",
		"link_to": SIDEBAR_NAME,
		"parent_icon": DESKTOP_ICON_PARENT,
		"app": "jey_theme",
		"standard": 1,
		"hidden": 0,
		"idx": DESKTOP_ICON_IDX,
	})
	icon.insert(ignore_permissions=True)
	return f"created Desktop Icon {DESKTOP_ICON_LABEL!r}"


def setup():
	"""Entry point — safe to call repeatedly (e.g. from after_migrate)."""
	results = [
		_cleanup_obsolete_workspace(),
		ensure_workspace_sidebar(),
		ensure_desktop_icon(),
	]
	frappe.db.commit()
	for r in results:
		if r:
			print(r)
