from __future__ import annotations import json import re from collections.abc import Iterable from typing import Any from uuid import UUID from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession from app.features.content.db_schema import CONTENT_SCHEMA, resolve_content_schema from .domain import FacetDefinitionRecord, FacetMappingRecord, ProjectionValue from .errors import FacetNotFoundError from .schema import FacetFilter, FacetValueMode, FilterLogic, SearchScope _SLUG_RE = re.compile(r"[^a-z0-9]+") def _slugify(value: str) -> str: return _SLUG_RE.sub("-", value.strip().lower()).strip("-") def _string_value(value: Any) -> str | None: if value is None: return None if isinstance(value, str): return value.strip() or None if isinstance(value, (int, float, bool)): return str(value) if isinstance(value, dict): for key in ("label", "name", "title", "value", "code"): candidate = value.get(key) if isinstance(candidate, (str, int, float, bool)) and str(candidate).strip(): return str(candidate).strip() return None return None def _flatten_projection_values(value: Any, json_path: Any = None) -> list[str]: if value is None: return [] if isinstance(value, list): result: list[str] = [] for item in value: result.extend(_flatten_projection_values(item, json_path)) return result if isinstance(value, dict): if json_path: paths = [json_path] if isinstance(json_path, str) else list(json_path) extracted: list[str] = [] for p in paths: sub_val = value.get(p) if sub_val is not None: extracted.extend(_flatten_projection_values(sub_val)) if extracted: return extracted direct = _string_value(value) if direct: return [direct] result = [] for item in value.values(): result.extend(_flatten_projection_values(item)) return result direct = _string_value(value) return [direct] if direct else [] class SearchRepository: def __init__(self, session: AsyncSession, schema: str = CONTENT_SCHEMA) -> None: self.session = session self.schema = resolve_content_schema(schema) async def list_facets( self, scope: SearchScope | None = None, ) -> list[FacetDefinitionRecord]: effective_scope = scope or SearchScope() params: dict[str, Any] = {} scope_sql = self._scope_sql(effective_scope, params) scope_exists = "" if scope_sql: scope_exists = f""" and exists ( select 1 from {self.schema}.content_search_facets scoped_csf join {self.schema}.content_items ci on ci.id = scoped_csf.content_id join {self.schema}.content_search_documents scoped_csd on scoped_csd.content_id = ci.id where scoped_csf.facet_id = sfd.id and ci.is_active = true and ci.status = 'published' and {scope_sql} ) """ result = await self.session.execute( text( f""" select sfd.id, sfd.code, sfd.label, sfd.category, sfd.description, sfd.control_type, sfd.allow_multiple_values, sfd.value_source, sfd.sort_order, sfd.metadata from {self.schema}.search_facet_definitions sfd where sfd.is_active = true {scope_exists} order by sfd.category, sfd.sort_order, sfd.label, sfd.code """ ), params, ) return [ FacetDefinitionRecord( id=row["id"], code=row["code"], label=row["label"], category=row["category"], description=row["description"], control_type=row["control_type"], allow_multiple_values=row["allow_multiple_values"], value_source=row["value_source"], sort_order=row["sort_order"], metadata=dict(row["metadata"] or {}), ) for row in result.mappings() ] async def get_facet(self, code: str) -> FacetDefinitionRecord: result = await self.session.execute( text( f""" select id, code, label, category, description, control_type, allow_multiple_values, value_source, sort_order, metadata from {self.schema}.search_facet_definitions where code = :code and is_active = true """ ), {"code": code.strip().lower()}, ) row = result.mappings().one_or_none() if row is None: raise FacetNotFoundError(f"Unknown active facet: {code}") return FacetDefinitionRecord( id=row["id"], code=row["code"], label=row["label"], category=row["category"], description=row["description"], control_type=row["control_type"], allow_multiple_values=row["allow_multiple_values"], value_source=row["value_source"], sort_order=row["sort_order"], metadata=dict(row["metadata"] or {}), ) async def list_modules( self, scope: SearchScope | None = None, ) -> list[dict[str, Any]]: effective_scope = scope or SearchScope() params: dict[str, Any] = {} where = ["is_active = true", "status = 'active'"] if effective_scope.module_codes: params["capability_module_codes"] = [ code.strip().lower() for code in effective_scope.module_codes if code and code.strip() ] where.append("code = any(cast(:capability_module_codes as text[]))") result = await self.session.execute( text( f""" select id, code, name, slug from {self.schema}.modules where {' and '.join(where)} order by name, id """ ), params, ) return [dict(row) for row in result.mappings()] async def list_content_kinds( self, scope: SearchScope | None = None, ) -> list[str]: effective_scope = scope or SearchScope() params: dict[str, Any] = {} where = [ "ci.content_kind is not null", "ci.is_active = true", "ci.status = 'published'", ] scope_sql = self._scope_sql(effective_scope, params) if scope_sql: where.append(scope_sql) result = await self.session.execute( text( f""" select distinct ci.content_kind::text as content_kind from {self.schema}.content_search_documents csd join {self.schema}.content_items ci on ci.id = csd.content_id where {' and '.join(where)} order by content_kind """ ), params, ) return [str(row[0]) for row in result.fetchall() if row[0]] async def list_mappings_for_content(self, content_id: UUID) -> list[FacetMappingRecord]: result = await self.session.execute( text( f""" select sfm.id, sfm.facet_id, sfd.code as facet_code, sfm.attribute_definition_id, ad.attribute_key, ads.code as template_code, m.code as module_code, sfm.content_kind, sfm.mapping_strategy, sfm.weight, sfm.metadata from {self.schema}.content_items ci join {self.schema}.attribute_definition_sets ads on ads.id = ci.attribute_definition_set_id join {self.schema}.search_facet_mappings sfm on sfm.attribute_definition_id in ( select ad2.id from {self.schema}.attribute_definitions ad2 where ad2.attribute_definition_set_id = ci.attribute_definition_set_id and ad2.is_active = true ) and sfm.is_active = true join {self.schema}.search_facet_definitions sfd on sfd.id = sfm.facet_id and sfd.is_active = true join {self.schema}.attribute_definitions ad on ad.id = sfm.attribute_definition_id left join {self.schema}.modules m on m.id = sfm.module_id where ci.id = :content_id and (sfm.module_id is null or exists ( select 1 from {self.schema}.module_contents mc where mc.content_id = ci.id and mc.module_id = sfm.module_id )) and (sfm.content_kind is null or sfm.content_kind = ci.content_kind::text) order by sfd.sort_order, sfm.sort_order, ad.sort_order """ ), {"content_id": content_id}, ) return [ FacetMappingRecord( id=row["id"], facet_id=row["facet_id"], facet_code=row["facet_code"], attribute_definition_id=row["attribute_definition_id"], attribute_key=row["attribute_key"], template_code=row["template_code"], module_code=row["module_code"], content_kind=row["content_kind"], mapping_strategy=row["mapping_strategy"], weight=float(row["weight"]), metadata=dict(row["metadata"] or {}), ) for row in result.mappings() ] async def _attribute_values_for_mapping( self, *, content_id: UUID, mapping: FacetMappingRecord ) -> list[Any]: result = await self.session.execute( text( f""" select ca.value_text, ca.value_number, ca.value_boolean, ca.value_date, ca.value_json from {self.schema}.content_attributes ca where ca.content_id = :content_id and ca.attribute_definition_id = :attribute_definition_id order by ca.created_at, ca.id """ ), { "content_id": content_id, "attribute_definition_id": mapping.attribute_definition_id, }, ) values: list[Any] = [] for row in result.mappings(): if row["value_json"] is not None: values.append(row["value_json"]) elif row["value_text"] is not None: values.append(row["value_text"]) elif row["value_number"] is not None: values.append(row["value_number"]) elif row["value_boolean"] is not None: values.append(row["value_boolean"]) elif row["value_date"] is not None: values.append(row["value_date"].isoformat()) return values def _project_value( self, raw: Any, strategy: str, metadata: dict[str, Any] | None = None, ) -> list[ProjectionValue]: strategy = strategy.strip().lower() json_path = (metadata or {}).get("json_path") or (metadata or {}).get("json_key") raw_values = _flatten_projection_values(raw, json_path=json_path) if strategy in ("multivalue", "comma_delimited", "delimited"): split_values: list[str] = [] for item in raw_values: if "," in item or ";" in item: for token in item.replace(";", ",").split(","): cleaned = token.strip().rstrip(".").strip() if cleaned: cleaned = cleaned[:1].upper() + cleaned[1:] split_values.append(cleaned) else: cleaned = item.strip().rstrip(".").strip() if cleaned: cleaned = cleaned[:1].upper() + cleaned[1:] split_values.append(cleaned) raw_values = split_values projected: list[ProjectionValue] = [] seen: set[str] = set() for label in raw_values: normalized_label = label.strip() if not normalized_label: continue key = _slugify(normalized_label) if not key or key in seen: continue seen.add(key) projected.append( ProjectionValue( value_key=key, value_label=normalized_label, value_text=normalized_label, source_value=raw, ) ) return projected async def rebuild_content_projection(self, content_id: UUID) -> int: """Rebuild one published content item's search document and facet rows.""" content_result = await self.session.execute( text( f""" select ci.id, ci.title, ci.summary, ci.content_kind::text as content_kind, ads.code as template_code, ads.is_filterable from {self.schema}.content_items ci join {self.schema}.attribute_definition_sets ads on ads.id = ci.attribute_definition_set_id where ci.id = :content_id and ci.is_active = true and ci.status = 'published' and ads.is_searchable = true """ ), {"content_id": content_id}, ) content = content_result.mappings().one_or_none() if content is None: # A non-searchable/unpublished/inactive template must leave no stale # search document or facet projection behind. await self.session.execute( text(f"delete from {self.schema}.content_search_facets where content_id = :content_id"), {"content_id": content_id}, ) await self.session.execute( text(f"delete from {self.schema}.content_search_documents where content_id = :content_id"), {"content_id": content_id}, ) return 0 text_result = await self.session.execute( text( f""" select string_agg(ca.value_text, ' ' order by ad.sort_order, ca.id) as body from {self.schema}.content_attributes ca join {self.schema}.attribute_definitions ad on ad.id = ca.attribute_definition_id where ca.content_id = :content_id and ad.is_active = true and ad.is_searchable = true and ad.definition_kind = 'scalar' and ca.value_text is not null """ ), {"content_id": content_id}, ) body = text_result.scalar_one_or_none() or "" search_text = " ".join( value for value in (content["title"], content["summary"], body) if value ) await self.session.execute( text( f""" insert into {self.schema}.content_search_documents ( content_id, template_code, search_text, search_vector, indexed_at ) values ( :content_id, :template_code, :search_text, to_tsvector('simple', :search_text), now() ) on conflict (content_id) do update set template_code = excluded.template_code, search_text = excluded.search_text, search_vector = excluded.search_vector, indexed_at = now() """ ), { "content_id": content_id, "template_code": content["template_code"], "search_text": search_text, }, ) await self.session.execute( text(f"delete from {self.schema}.content_search_facets where content_id = :content_id"), {"content_id": content_id}, ) mappings = ( await self.list_mappings_for_content(content_id) if content["is_filterable"] else [] ) inserted = 0 for mapping in mappings: raw_rows = await self._attribute_values_for_mapping( content_id=content_id, mapping=mapping, ) values: list[ProjectionValue] = [] for raw in raw_rows: values.extend( self._project_value( raw, mapping.mapping_strategy, metadata=mapping.metadata, ) ) seen: set[str] = set() for value in values: if value.value_key in seen: continue seen.add(value.value_key) await self.session.execute( text( f""" insert into {self.schema}.content_search_facets ( content_id, facet_id, mapping_id, value_key, value_label, value_text, source_attribute_definition_id, source_value, indexed_at ) values ( :content_id, :facet_id, :mapping_id, :value_key, :value_label, :value_text, :attribute_definition_id, cast(:source_value as jsonb), now() ) on conflict (content_id, facet_id, mapping_id, value_key) do update set value_label = excluded.value_label, value_text = excluded.value_text, source_value = excluded.source_value, indexed_at = now() """ ), { "content_id": content_id, "facet_id": mapping.facet_id, "mapping_id": mapping.id, "value_key": value.value_key, "value_label": value.value_label, "value_text": value.value_text, "attribute_definition_id": mapping.attribute_definition_id, "source_value": json.dumps(value.source_value, default=str), }, ) inserted += 1 return inserted async def rebuild_all(self, module_codes: list[str] | None = None) -> tuple[int, int]: params: dict[str, Any] = {} module_clause = "" if module_codes: params["module_codes"] = [ code.strip().lower() for code in module_codes if code and code.strip() ] module_clause = f""" and exists ( select 1 from {self.schema}.module_contents mc join {self.schema}.modules m on m.id = mc.module_id where mc.content_id = ci.id and m.code = any(cast(:module_codes as text[])) ) """ result = await self.session.execute( text( f""" select ci.id from {self.schema}.content_items ci where ci.is_active = true and ci.status = 'published' {module_clause} order by ci.id """ ), params, ) ids = [row[0] for row in result.fetchall()] facet_rows = 0 for content_id in ids: facet_rows += await self.rebuild_content_projection(content_id) return len(ids), facet_rows def _scope_sql(self, scope: SearchScope, params: dict[str, Any], *, ci_alias: str = "ci") -> str: clauses: list[str] = [] if scope.module_codes: params["scope_module_codes"] = [ code.strip().lower() for code in scope.module_codes if code and code.strip() ] clauses.append( f"""exists ( select 1 from {self.schema}.module_contents scope_mc join {self.schema}.modules scope_m on scope_m.id = scope_mc.module_id where scope_mc.content_id = {ci_alias}.id and scope_m.code = any(cast(:scope_module_codes as text[])) and scope_m.is_active = true )""" ) if scope.content_kinds: params["scope_content_kinds"] = scope.content_kinds clauses.append(f"{ci_alias}.content_kind::text = any(:scope_content_kinds)") return " and ".join(clauses) def _filter_sql( self, filters: list[FacetFilter], logic: FilterLogic, params: dict[str, Any], *, ci_alias: str = "ci", ignore_facet_code: str | None = None, ) -> str: pieces: list[str] = [] serial = 0 for item in filters: if ignore_facet_code and item.facet_code == ignore_facet_code: continue facet_param = f"filter_facet_{serial}" values_param = f"filter_values_{serial}" params[facet_param] = item.facet_code params[values_param] = item.values if item.value_mode == FacetValueMode.ALL: pieces.append( f"""( select count(distinct csf.value_key) from {self.schema}.content_search_facets csf join {self.schema}.search_facet_definitions sfd on sfd.id = csf.facet_id where csf.content_id = {ci_alias}.id and sfd.code = :{facet_param} and csf.value_key = any(:{values_param}) ) = :filter_value_count_{serial}""" ) params[f"filter_value_count_{serial}"] = len(item.values) else: pieces.append( f"""exists ( select 1 from {self.schema}.content_search_facets csf join {self.schema}.search_facet_definitions sfd on sfd.id = csf.facet_id where csf.content_id = {ci_alias}.id and sfd.code = :{facet_param} and csf.value_key = any(:{values_param}) )""" ) serial += 1 if not pieces: return "" joiner = " and " if logic == FilterLogic.AND else " or " return "(" + joiner.join(pieces) + ")" async def facet_values( self, *, facet_code: str, scope: SearchScope, query: str | None, active_filters: list[FacetFilter], filter_logic: FilterLogic, limit: int, ) -> list[dict[str, Any]]: facet = await self.get_facet(facet_code) params: dict[str, Any] = {"facet_id": facet.id, "limit": limit} where = ["ci.is_active = true", "ci.status = 'published'"] scope_sql = self._scope_sql(scope, params) if scope_sql: where.append(scope_sql) filters_sql = self._filter_sql( active_filters, filter_logic, params, ignore_facet_code=facet_code, ) if filters_sql: where.append(filters_sql) value_where = ["csf.facet_id = :facet_id"] if query: params["typeahead_query"] = f"%{query.strip()}%" value_where.append("csf.value_label ilike :typeahead_query") result = await self.session.execute( text( f""" with candidates as ( select ci.id from {self.schema}.content_items ci join {self.schema}.content_search_documents csd on csd.content_id = ci.id where {' and '.join(where)} ) select csf.value_key, min(csf.value_label) as label, count(distinct csf.content_id)::int as result_count from {self.schema}.content_search_facets csf join candidates c on c.id = csf.content_id where {' and '.join(value_where)} group by csf.value_key order by result_count desc, label asc limit :limit """ ), params, ) return [dict(row) for row in result.mappings()] async def search( self, *, scope: SearchScope, query: str | None, filters: list[FacetFilter], filter_logic: FilterLogic, sort_field: str, sort_direction: str, page: int, page_size: int, ) -> tuple[int, list[dict[str, Any]]]: params: dict[str, Any] = { "limit": page_size, "offset": (page - 1) * page_size, } where = ["ci.is_active = true", "ci.status = 'published'"] scope_sql = self._scope_sql(scope, params) if scope_sql: where.append(scope_sql) filter_sql = self._filter_sql(filters, filter_logic, params) if filter_sql: where.append(filter_sql) score_expr = "0.0" if query: params["search_query"] = query where.append("csd.search_vector @@ websearch_to_tsquery('simple', :search_query)") score_expr = "ts_rank_cd(csd.search_vector, websearch_to_tsquery('simple', :search_query))" direction = "asc" if sort_direction == "asc" else "desc" if sort_field == "title": order_sql = f"r.title {direction}, r.id asc" elif sort_field == "recent": order_sql = f"r.published_at {direction} nulls last, r.id asc" else: order_sql = f"r.score desc, r.title asc, r.id asc" where_sql = " and ".join(where) count_result = await self.session.execute( text( f""" select count(distinct ci.id) from {self.schema}.content_items ci join {self.schema}.content_search_documents csd on csd.content_id = ci.id where {where_sql} """ ), params, ) total = int(count_result.scalar_one()) result = await self.session.execute( text( f""" with ranked as ( select ci.id, ci.content_kind::text as content_kind, ci.title, ci.summary, ci.published_at, csd.template_code, ads.name as template_name, {score_expr} as score from {self.schema}.content_items ci join {self.schema}.content_search_documents csd on csd.content_id = ci.id join {self.schema}.attribute_definition_sets ads on ads.id = ci.attribute_definition_set_id where {where_sql} ), module_choice as ( select distinct on (mc.content_id) mc.content_id, m.code as module_code, m.name as module_name from {self.schema}.module_contents mc join {self.schema}.modules m on m.id = mc.module_id where m.is_active = true {"and m.code = any(:scope_module_codes)" if scope.module_codes else ""} order by mc.content_id, mc.sort_order, m.code ) select r.*, mc.module_code, mc.module_name from ranked r join module_choice mc on mc.content_id = r.id order by {order_sql} limit :limit offset :offset """ ), params, ) return total, [dict(row) for row in result.mappings()]