"""Rename the Bank Integration DocType to Bank Statement Importer.

The doctype was originally named "Bank Integration" but that label is too broad
— this is specifically a configurable Excel statement importer, not a generic
bank integration. Renaming clarifies its purpose in the UI and brings the
record name in line with the new workspace.

This patch is idempotent: it only runs if the old DocType still exists and the
new one doesn't, so re-running migrate is safe.

Runs in [pre_model_sync] so the rename happens BEFORE Frappe tries to reload
the JSON definition (which already declares the new name).
"""

import frappe


def execute():
	old_name = "Bank Integration"
	new_name = "Bank Statement Importer"

	if frappe.db.exists("DocType", new_name):
		# Either the rename already ran or someone created it from scratch.
		# Nothing to do.
		return

	if not frappe.db.exists("DocType", old_name):
		# Fresh install / already-renamed environment.
		return

	# frappe.rename_doc on a DocType:
	#   - renames the underlying `tab<Name>` table
	#   - updates Link/Dynamic Link references stored in DocField.options
	#   - updates `parent` / `parenttype` rows in linked child tables
	frappe.rename_doc("DocType", old_name, new_name, force=True, show_alert=False)

	# Dynamic Link values are NOT updated by rename_doc (they live in user data,
	# not metadata). Hand-update the Bank Account.bank_integration_type column.
	frappe.db.sql(
		"""UPDATE `tabBank Account`
		   SET bank_integration_type = %s
		   WHERE bank_integration_type = %s""",
		(new_name, old_name),
	)

	# Same for the Select options on the bank_integration_type Custom Field — the
	# JSON-defined custom_fields.py rewrites this on the next after_migrate, but
	# do it here too so the rest of this same migrate run sees consistent values.
	custom_field = frappe.db.exists("Custom Field", {
		"dt": "Bank Account", "fieldname": "bank_integration_type"
	})
	if custom_field:
		frappe.db.set_value(
			"Custom Field", custom_field, "options",
			"\n" + new_name + "\nKapital Bank Settings",
			update_modified=False,
		)

	frappe.db.commit()
	print(f"BI: renamed DocType '{old_name}' to '{new_name}'")
