import frappe


def execute():
	"""Remove old agricultural fields and hide E-Taxes Purchase Act ID field"""

	# List of old fields to delete (already migrated to new fields)
	# These fields were migrated by rename_agricultural_to_purchase_type patch:
	# - agricultural_goods → purchase_type
	# - purchase_confirmation_doc_type → act_type
	# - agricultural_country was never used and should be removed
	old_fields_to_delete = [
		"agricultural_goods",
		"agricultural_country",
		"purchase_confirmation_doc_type"
	]

	# Doctypes to clean up
	doctypes = ["Purchase Invoice", "Purchase Order"]

	# Delete old custom fields
	deleted_count = 0
	for doctype in doctypes:
		for fieldname in old_fields_to_delete:
			try:
				field_name = f"{doctype}-{fieldname}"
				if frappe.db.exists("Custom Field", field_name):
					frappe.delete_doc("Custom Field", field_name, force=True, ignore_permissions=True)
					deleted_count += 1
					print(f"Deleted custom field: {field_name}")
			except Exception as e:
				print(f"Error deleting {field_name}: {str(e)}")

	if deleted_count > 0:
		frappe.db.commit()
		print(f"Committed deletion of {deleted_count} fields")

	# Hide E-Taxes Purchase Act ID field in Purchase Invoice
	try:
		field_name = "Purchase Invoice-etaxes_purchase_id"
		if frappe.db.exists("Custom Field", field_name):
			field_doc = frappe.get_doc("Custom Field", field_name)
			if not field_doc.hidden:
				field_doc.hidden = 1
				field_doc.flags.ignore_validate = True
				field_doc.save(ignore_permissions=True)
				frappe.db.commit()
				print(f"Hidden field: {field_name}")
			else:
				print(f"Field already hidden: {field_name}")
	except Exception as e:
		print(f"Error hiding etaxes_purchase_id: {str(e)}")

	# Fix section placement to prevent standard ERPNext fields (is_return, apply_tds, amended_from)
	# from appearing in the E-Taxes section
	# Correct order:
	#   amended_from (standard)
	#   is_taxes_doc (custom)
	#   purchase_type (custom)
	#   act_type (custom)
	#   etaxes_agricultural_section (Section Break)
	#   act_kind, etaxes_purchase_id, etc.

	# Move is_taxes_doc to after amended_from
	try:
		is_taxes_field_name = "Purchase Invoice-is_taxes_doc"
		if frappe.db.exists("Custom Field", is_taxes_field_name):
			is_taxes_doc = frappe.get_doc("Custom Field", is_taxes_field_name)
			if is_taxes_doc.insert_after != "amended_from":
				is_taxes_doc.insert_after = "amended_from"
				is_taxes_doc.flags.ignore_validate = True
				is_taxes_doc.save(ignore_permissions=True)
				frappe.db.commit()
				print(f"Moved is_taxes_doc to after 'amended_from': {is_taxes_field_name}")
			else:
				print(f"is_taxes_doc already in correct position: {is_taxes_field_name}")
	except Exception as e:
		print(f"Error moving is_taxes_doc: {str(e)}")

	# Move etaxes_agricultural_section to after act_type (not amended_from!)
	try:
		section_field_name = "Purchase Invoice-etaxes_agricultural_section"
		if frappe.db.exists("Custom Field", section_field_name):
			section_doc = frappe.get_doc("Custom Field", section_field_name)
			if section_doc.insert_after != "act_type":
				section_doc.insert_after = "act_type"
				section_doc.flags.ignore_validate = True
				section_doc.save(ignore_permissions=True)
				frappe.db.commit()
				print(f"Moved section to after 'act_type': {section_field_name}")
			else:
				print(f"Section already in correct position: {section_field_name}")
	except Exception as e:
		print(f"Error moving section: {str(e)}")

	# Clear cache to apply changes
	frappe.clear_cache()
	print("Cache cleared. Old agricultural fields removed, E-Taxes Purchase Act ID hidden, and section placement fixed.")
