import frappe
from frappe.utils.password import decrypt, get_decrypted_password, set_encrypted_password


def execute():
	"""Migrate the Kapital Bank Login `password` field from plain Data to an
	encrypted Password field.

	The encrypted secret is stored in the `__Auth` table and the doctype column
	is masked, so `doc.get_password("password")` transparently decrypts it.
	Idempotent: skips records already migrated, and recovers from an earlier
	revision of this patch that mistakenly wrote ciphertext into the column."""
	if not frappe.db.exists("DocType", "Kapital Bank Login"):
		return

	for name in frappe.get_all("Kapital Bank Login", pluck="name"):
		# Already stored in __Auth → nothing to do.
		if get_decrypted_password("Kapital Bank Login", name, "password", raise_exception=False):
			continue

		col = frappe.db.get_value("Kapital Bank Login", name, "password")
		if not col:
			continue

		# Recover the real password: clear text is used as-is; ciphertext left by
		# an earlier run of this patch is decrypted back first.
		plaintext = col
		try:
			recovered = decrypt(col)
			if recovered:
				plaintext = recovered
		except Exception:
			plaintext = col

		set_encrypted_password("Kapital Bank Login", name, plaintext, "password")
		frappe.db.set_value(
			"Kapital Bank Login", name, "password", "*" * len(plaintext), update_modified=False
		)

	frappe.db.commit()
