# Copyright (c) 2025, JINGROW and contributors
# For license information, please see license.txt

import jingrow
from jingrow import _
from jingrow.model.page import Page
from jingrow.desk.form.linked_with import get_linked_pgs, get_linked_pagetypes
from jingrow.exceptions import LinkExistsError


class DeleteRecord(Page):
	# begin: auto-generated types
	# This code is auto-generated. Do not modify anything in this block.

	from typing import TYPE_CHECKING

	if TYPE_CHECKING:
		from jingrow.types import DF

		record_name: DF.Data | None
		pagetype: DF.Link | None
	# end: auto-generated types
	pass


def _delete_with_dependencies(pagetype, record_name, visited=None):
	if visited is None:
		visited = set()
	key = f"{pagetype}::{record_name}"
	if key in visited:
		return
	visited.add(key)

	# 获取所有直接关联
	linkinfo = get_linked_pagetypes(pagetype)
	if linkinfo:
		linked_pgs = get_linked_pgs(pagetype, record_name, linkinfo)
		for linked_pagetype, pgs in linked_pgs.items():
			for pg in pgs:
				_delete_with_dependencies(linked_pagetype, pg.name, visited)

	# 删除自己
	try:
		jingrow.delete_pg(
			pagetype,
			record_name,
			force=True,
			ignore_permissions=True,
			delete_permanently=True
		)
	except LinkExistsError as e:
		jingrow.log_error(_("跳过删除受保护的记录"), f"{pagetype} - {record_name}: {str(e)}")
		# 跳过受保护的记录
	except Exception as e:
		jingrow.throw(_("删除记录失败: {0}").format(str(e)))


@jingrow.whitelist()
def delete_record_with_dependencies(pagetype, record_name):
	"""递归删除记录及其所有关联记录，先删子级再删父级，受保护的记录跳过"""
	if not pagetype or not record_name:
		jingrow.throw(_("PageType 和 Record Name 不能为空"))
	_delete_with_dependencies(pagetype, record_name)
