import jingrow


def execute():
	jingrow.delete_pg_if_exists("PageType", "Tag Category")
	jingrow.delete_pg_if_exists("PageType", "Tag Pg Category")

	jingrow.reload_pg("desk", "pagetype", "tag")
	jingrow.reload_pg("desk", "pagetype", "tag_link")

	tag_list = []
	tag_links = []
	time = jingrow.utils.get_datetime()

	for pagetype in jingrow.get_list("PageType", filters={"istable": 0, "issingle": 0, "is_virtual": 0}):
		if not jingrow.db.count(pagetype.name) or not jingrow.db.has_column(pagetype.name, "_user_tags"):
			continue

		for _user_tags in jingrow.db.sql(
			f"select `name`, `_user_tags` from `tab{pagetype.name}`", as_dict=True
		):
			if not _user_tags.get("_user_tags"):
				continue

			for tag in _user_tags.get("_user_tags").split(",") if _user_tags.get("_user_tags") else []:
				if not tag:
					continue

				tag_list.append((tag.strip(), time, time, "Administrator"))

				tag_link_name = jingrow.generate_hash(length=10)
				tag_links.append(
					(tag_link_name, pagetype.name, _user_tags.name, tag.strip(), time, time, "Administrator")
				)

	jingrow.db.bulk_insert(
		"Tag",
		fields=["name", "creation", "modified", "modified_by"],
		values=set(tag_list),
		ignore_duplicates=True,
	)
	jingrow.db.bulk_insert(
		"Tag Link",
		fields=["name", "document_type", "document_name", "tag", "creation", "modified", "modified_by"],
		values=set(tag_links),
		ignore_duplicates=True,
	)
