# Copyright (c) 2015, JINGROW and Contributors
# License: MIT. See LICENSE

import json
import re
from typing import TypedDict

from typing_extensions import NotRequired  # not required in 3.11+

import jingrow

# Backward compatbility
from jingrow import _, is_whitelisted, validate_and_sanitize_search_inputs
from jingrow.database.schema import SPECIAL_CHAR_PATTERN
from jingrow.model.db_query import get_order_by
from jingrow.permissions import has_permission
from jingrow.utils import cint, cstr, unique
from jingrow.utils.data import make_filter_tuple


def sanitize_searchfield(searchfield: str):
	if not searchfield:
		return

	if SPECIAL_CHAR_PATTERN.search(searchfield):
		jingrow.throw(_("Invalid Search Field {0}").format(searchfield), jingrow.DataError)


class LinkSearchResults(TypedDict):
	value: str
	description: str
	label: NotRequired[str]


# this is called by the Link Field
@jingrow.whitelist()
def search_link(
	pagetype: str,
	txt: str,
	query: str | None = None,
	filters: str | dict | list | None = None,
	page_length: int = 10,
	searchfield: str | None = None,
	reference_pagetype: str | None = None,
	ignore_user_permissions: bool = False,
) -> list[LinkSearchResults]:
	results = search_widget(
		pagetype,
		txt.strip(),
		query,
		searchfield=searchfield,
		page_length=page_length,
		filters=filters,
		reference_pagetype=reference_pagetype,
		ignore_user_permissions=ignore_user_permissions,
	)
	return build_for_autosuggest(results, pagetype=pagetype)


# this is called by the search box
@jingrow.whitelist()
def search_widget(
	pagetype: str,
	txt: str,
	query: str | None = None,
	searchfield: str | None = None,
	start: int = 0,
	page_length: int = 10,
	filters: str | None | dict | list = None,
	filter_fields=None,
	as_dict: bool = False,
	reference_pagetype: str | None = None,
	ignore_user_permissions: bool = False,
):
	start = cint(start)

	if isinstance(filters, str):
		filters = json.loads(filters)

	if searchfield:
		sanitize_searchfield(searchfield)

	if not searchfield:
		searchfield = "name"

	standard_queries = jingrow.get_hooks().standard_queries or {}

	if not query and pagetype in standard_queries:
		query = standard_queries[pagetype][-1]

	if query:  # Query = custom search query i.e. python function
		try:
			is_whitelisted(jingrow.get_attr(query))
			return jingrow.call(
				query,
				pagetype,
				txt,
				searchfield,
				start,
				page_length,
				filters,
				as_dict=as_dict,
				reference_pagetype=reference_pagetype,
				ignore_user_permissions=ignore_user_permissions,
			)
		except (jingrow.PermissionError, jingrow.AppNotInstalledError, ImportError):
			if jingrow.local.conf.developer_mode:
				raise
			else:
				jingrow.respond_as_web_page(
					title="Invalid Method",
					html="Method not found",
					indicator_color="red",
					http_status_code=404,
				)
				return []

	meta = jingrow.get_meta(pagetype)

	if isinstance(filters, dict):
		filters_items = filters.items()
		filters = []
		for key, value in filters_items:
			filters.append(make_filter_tuple(pagetype, key, value))

	if filters is None:
		filters = []
	or_filters = []

	# build from pagetype
	if txt:
		field_types = {
			"Data",
			"Text",
			"Small Text",
			"Long Text",
			"Link",
			"Select",
			"Read Only",
			"Text Editor",
		}
		search_fields = ["name"]
		if meta.title_field:
			search_fields.append(meta.title_field)

		if meta.search_fields:
			search_fields.extend(meta.get_search_fields())

		for f in search_fields:
			fmeta = meta.get_field(f.strip())
			if not meta.translated_pagetype and (f == "name" or (fmeta and fmeta.fieldtype in field_types)):
				or_filters.append([pagetype, f.strip(), "like", f"%{txt}%"])

	if meta.get("fields", {"fieldname": "enabled", "fieldtype": "Check"}):
		filters.append([pagetype, "enabled", "=", 1])
	if meta.get("fields", {"fieldname": "disabled", "fieldtype": "Check"}):
		filters.append([pagetype, "disabled", "!=", 1])

	# format a list of fields combining search fields and filter fields
	fields = get_std_fields_list(meta, searchfield or "name")
	if filter_fields:
		fields = list(set(fields + json.loads(filter_fields)))
	formatted_fields = [f"`tab{meta.name}`.`{f.strip()}`" for f in fields]

	# Insert title field query after name
	if meta.show_title_field_in_link and meta.title_field:
		formatted_fields.insert(1, f"`tab{meta.name}`.{meta.title_field} as `label`")

	order_by_based_on_meta = get_order_by(pagetype, meta)
	# `idx` is number of times a document is referred, check link_count.py
	order_by = f"`tab{pagetype}`.idx desc, {order_by_based_on_meta}"

	if not meta.translated_pagetype:
		_txt = jingrow.db.escape((txt or "").replace("%", "").replace("@", ""))
		# locate returns 0 if string is not found, convert 0 to null and then sort null to end in order by
		_relevance = f"(1 / nullif(locate({_txt}, `tab{pagetype}`.`name`), 0))"
		formatted_fields.append(f"""{_relevance} as `_relevance`""")
		# Since we are sorting by alias postgres needs to know number of column we are sorting
		if jingrow.db.db_type == "mariadb":
			order_by = f"ifnull(_relevance, -9999) desc, {order_by}"
		elif jingrow.db.db_type == "postgres":
			# Since we are sorting by alias postgres needs to know number of column we are sorting
			order_by = f"{len(formatted_fields)} desc nulls last, {order_by}"

	ignore_permissions = pagetype == "PageType" or (
		cint(ignore_user_permissions)
		and has_permission(
			pagetype,
			ptype="select" if jingrow.only_has_select_perm(pagetype) else "read",
			parent_pagetype=reference_pagetype,
		)
	)

	values = jingrow.get_list(
		pagetype,
		filters=filters,
		fields=formatted_fields,
		or_filters=or_filters,
		limit_start=start,
		limit_page_length=None if meta.translated_pagetype else page_length,
		order_by=order_by,
		ignore_permissions=ignore_permissions,
		reference_pagetype=reference_pagetype,
		as_list=not as_dict,
		strict=False,
	)

	if meta.translated_pagetype:
		# Filtering the values array so that query is included in very element
		# Match both original value and translated value to support search in any language
		values = (
			result
			for result in values
			if any(
				re.search(f"{re.escape(txt)}.*", _(cstr(value)) or "", re.IGNORECASE) or
				re.search(f"{re.escape(txt)}.*", cstr(value) or "", re.IGNORECASE)
				for value in (result.values() if as_dict else result)
			)
		)
		# Convert generator to list for sorting and pagination
		values = list(values)

	# Sorting the values array so that relevant results always come first
	# This will first bring elements on top in which query is a prefix of element
	# Then it will bring the rest of the elements and sort them in lexicographical order
	values = sorted(values, key=lambda x: relevance_sorter(x, txt, as_dict))

	# remove _relevance from results
	if not meta.translated_pagetype:
		if as_dict:
			for r in values:
				r.pop("_relevance", None)
		else:
			values = [r[:-1] for r in values]

	# Apply pagination for translated_pagetype after filtering and sorting
	if meta.translated_pagetype:
		values = values[start : start + page_length]

	return values


def get_std_fields_list(meta, key):
	# get additional search fields
	sflist = ["name"]

	if meta.title_field and meta.title_field not in sflist:
		sflist.append(meta.title_field)

	if key not in sflist:
		sflist.append(key)

	if meta.search_fields:
		for d in meta.search_fields.split(","):
			if d.strip() not in sflist:
				sflist.append(d.strip())

	return sflist


def build_for_autosuggest(res: list[tuple], pagetype: str) -> list[LinkSearchResults]:
	def to_string(parts):
		return ", ".join(
			unique(_(cstr(part)) if meta.translated_pagetype else cstr(part) for part in parts if part)
		)

	results = []
	meta = jingrow.get_meta(pagetype)
	if meta.show_title_field_in_link:
		for item in res:
			item = list(item)
			if len(item) == 1:
				item = [item[0], item[0]]
			
			title_value = item[1] if len(item) > 1 else item[0]
			name_value = item[0]
			
			if title_value and title_value.strip():
				results.append({"value": name_value, "label": title_value})
			else:
				results.append({"value": name_value, "label": name_value})
	else:
		results.extend({"value": item[0], "description": to_string(item[1:])} for item in res)

	return results


def scrub_custom_query(query, key, txt):
	if "%(key)s" in query:
		query = query.replace("%(key)s", key)
	if "%s" in query:
		query = query.replace("%s", ((txt or "") + "%"))
	return query


def relevance_sorter(key, query, as_dict):
	value = _(key.name if as_dict else key[0])
	return (cstr(value).casefold().startswith(query.casefold()) is not True, value)


@jingrow.whitelist()
def get_names_for_mentions(search_term):
	users_for_mentions = jingrow.cache.get_value("users_for_mentions", get_users_for_mentions)
	user_groups = jingrow.cache.get_value("user_groups", get_user_groups)

	filtered_mentions = []
	for mention_data in users_for_mentions + user_groups:
		if search_term.lower() not in mention_data.value.lower():
			continue

		mention_data["link"] = jingrow.utils.get_url_to_form(
			"User Group" if mention_data.get("is_group") else "User Profile", mention_data["id"]
		)

		filtered_mentions.append(mention_data)

	return sorted(filtered_mentions, key=lambda d: d["value"])


def get_users_for_mentions():
	return jingrow.get_all(
		"User",
		fields=["name as id", "full_name as value"],
		filters={
			"name": ["not in", ("Administrator", "Guest")],
			"allowed_in_mentions": True,
			"user_type": "System User",
			"enabled": True,
		},
	)


def get_user_groups():
	return jingrow.get_all("User Group", fields=["name as id", "name as value"], update={"is_group": True})


@jingrow.whitelist()
def get_link_title(pagetype, pagename):
	meta = jingrow.get_meta(pagetype)

	if meta.show_title_field_in_link:
		return jingrow.db.get_value(pagetype, pagename, meta.title_field)

	return pagename
