from __future__ import annotations import copy import io import json import logging import re import zipfile from datetime import datetime, timezone from pathlib import Path from typing import Any from fastapi import HTTPException from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.db.models import BuilderCategory, BuilderDisease, BuilderModule, BuilderPattern logger = logging.getLogger("acupedia.builder.compiler") DEFAULT_CONTENT_REPO_PATH = Path( "/home/cspl/urvish/CSPL/Panacea/acupedia_content/acupedia-content" ) class ModuleContentCompiler: """Compiles authored relational module content into the production-grade Acupedia multi-file repository structure (module.json, templates/, data/, search_facets.json). """ def __init__(self, session: AsyncSession) -> None: self.session = session async def compile_module(self, module_code: str) -> tuple[BuilderModule, dict[str, str]]: # 1. Fetch Module stmt = select(BuilderModule).where(BuilderModule.code == module_code) res = await self.session.execute(stmt) module = res.scalar_one_or_none() if not module: raise HTTPException( status_code=404, detail=f"Module '{module_code}' not found. Please create it first.", ) if module.kind != "therapeutic" or getattr(module, "managed_by", "module_builder") != "module_builder": raise HTTPException( status_code=403, detail=( f"Module '{module_code}' is not managed by Module Builder " f"(kind='{module.kind}', managed_by='{getattr(module, 'managed_by', None)}'). Cannot compile." ), ) # 2. Fetch Categories cat_stmt = ( select(BuilderCategory) .where(BuilderCategory.module_code == module_code) .order_by(BuilderCategory.sort_order, BuilderCategory.name) ) cat_res = await self.session.execute(cat_stmt) categories = list(cat_res.scalars().all()) if not categories: raise HTTPException( status_code=400, detail=( f"Cannot compile module '{module_code}': Please add at least one " "disease category before exporting or syncing." ), ) # 3. Fetch Diseases & Patterns per Category dis_stmt = ( select(BuilderDisease) .where(BuilderDisease.module_code == module_code) .order_by(BuilderDisease.sort_order, BuilderDisease.name) ) dis_res = await self.session.execute(dis_stmt) all_diseases = list(dis_res.scalars().all()) pat_stmt = ( select(BuilderPattern) .where(BuilderPattern.module_code == module_code) .order_by(BuilderPattern.sort_order, BuilderPattern.name) ) pat_res = await self.session.execute(pat_stmt) all_patterns = list(pat_res.scalars().all()) # Group diseases by category diseases_by_cat: dict[str, list[BuilderDisease]] = {c.category_code: [] for c in categories} for d in all_diseases: if d.category_code in diseases_by_cat: diseases_by_cat[d.category_code].append(d) # Group patterns by (category, disease) patterns_by_dis: dict[tuple[str, str], list[BuilderPattern]] = {} for p in all_patterns: key = (p.category_code, p.disease_code) if key not in patterns_by_dis: patterns_by_dis[key] = [] patterns_by_dis[key].append(p) # Validation: check empty diseases or empty categories for cat in categories: cat_dis = diseases_by_cat[cat.category_code] if not cat_dis: raise HTTPException( status_code=400, detail=( f"Cannot compile module '{module_code}': Category '{cat.name}' " "has no diseases. Please add at least one disease." ), ) for dis in cat_dis: dis_pats = patterns_by_dis.get((cat.category_code, dis.disease_code), []) if not dis_pats: raise HTTPException( status_code=400, detail=( f"Cannot compile module '{module_code}': Disease '{dis.name}' " f"(in category '{cat.name}') has no clinical patterns. " "Please add at least one pattern." ), ) # 4. Deterministic Template Allocation root_template_code = f"{module_code}_ct0001" detail_template_code = f"{module_code}_ct0005" cat_template_codes: dict[str, str] = {} curr_cat_num = 2 for cat in categories: if curr_cat_num == 5: curr_cat_num += 1 cat_template_codes[cat.category_code] = f"{module_code}_ct{curr_cat_num:04d}" curr_cat_num += 1 dis_template_codes: dict[tuple[str, str], str] = {} curr_dis_num = 11 for cat in categories: for dis in diseases_by_cat[cat.category_code]: dis_template_codes[(cat.category_code, dis.disease_code)] = f"{module_code}_ct{curr_dis_num:04d}" curr_dis_num += 1 files: dict[str, str] = {} content_mappings: list[dict[str, Any]] = [] # --------------------------------------------------------------------- # 5. Generate Root Templates & Files (Level 1) # --------------------------------------------------------------------- root_template = self._create_list_template( module_code=module_code, template_code=root_template_code, template_name=f"{module.slug.replace('-', '_')}_list_content", is_searchable=False, is_filterable=False, ) files[f"templates/{root_template_code}.json"] = json.dumps(root_template, indent=2) root_list_items = [] for idx, cat in enumerate(categories): cat_t_code = cat_template_codes[cat.category_code] cat_diseases = diseases_by_cat[cat.category_code] root_list_items.append({ "name": cat.name, "code": cat.category_code, "content_count": len(cat_diseases), "content_label": "diseases", "sort_order": idx, "link": { "type": "template_ref", "label": cat.name, "target": { "module_code": module_code, "template_code": cat_t_code, }, }, }) root_list_doc = {"contents": root_list_items} files["data/list.json"] = json.dumps(root_list_doc, indent=2) content_mappings.append({ "name": "module_list_content", "description": "", "code": root_template_code, "data_path": "data/list.json", "template_path": f"templates/{root_template_code}.json", }) # --------------------------------------------------------------------- # 6. Generate Category Templates & Files (Level 2) # --------------------------------------------------------------------- for cat in categories: cat_t_code = cat_template_codes[cat.category_code] cat_slug = re.sub(r"[^a-z0-9]+", "_", cat.category_code.lower()).strip("_") cat_template = self._create_list_template( module_code=module_code, template_code=cat_t_code, template_name=f"{cat_slug}_list_content", is_searchable=False, is_filterable=False, ) files[f"templates/{cat_t_code}.json"] = json.dumps(cat_template, indent=2) dis_list_items = [] for d_idx, dis in enumerate(diseases_by_cat[cat.category_code]): dis_t_code = dis_template_codes[(cat.category_code, dis.disease_code)] pats = patterns_by_dis[(cat.category_code, dis.disease_code)] dis_list_items.append({ "name": dis.name, "code": dis.disease_code, "content_count": len(pats), "content_label": "patterns", "sort_order": d_idx, "link": { "type": "template_ref", "label": dis.name, "target": { "module_code": module_code, "template_code": dis_t_code, }, }, }) cat_list_doc = {"contents": dis_list_items} cat_data_path = f"data/{cat.category_code}/list.json" files[cat_data_path] = json.dumps(cat_list_doc, indent=2) content_mappings.append({ "name": f"{cat_slug}_list_content", "description": "", "code": cat_t_code, "data_path": cat_data_path, "template_path": f"templates/{cat_t_code}.json", }) # --------------------------------------------------------------------- # 7. Generate Master Pattern Detail Template & Master Detail File (Level 4) # --------------------------------------------------------------------- detail_template = self._create_detail_template( module_code=module_code, template_code=detail_template_code, ) files[f"templates/{detail_template_code}.json"] = json.dumps(detail_template, indent=2) master_detail_items = [] global_pattern_sort = 0 # --------------------------------------------------------------------- # 8. Generate Disease Templates, Pattern Lists & data.json (Level 3) # --------------------------------------------------------------------- for cat in categories: for dis in diseases_by_cat[cat.category_code]: dis_t_code = dis_template_codes[(cat.category_code, dis.disease_code)] dis_slug = re.sub(r"[^a-z0-9]+", "_", dis.disease_code.lower()).strip("_") dis_template = self._create_list_template( module_code=module_code, template_code=dis_t_code, template_name=f"{dis_slug}_list_content", is_searchable=True, is_filterable=True, ) files[f"templates/{dis_t_code}.json"] = json.dumps(dis_template, indent=2) pat_list_items = [] embedded_patterns = [] pats = patterns_by_dis[(cat.category_code, dis.disease_code)] for p_idx, pat in enumerate(pats): source_code = f"{dis.disease_code}_{pat.pattern_code}" c_data = pat.clinical_data or {} # Item for disease pattern list pat_list_items.append({ "name": pat.name, "code": source_code, "sort_order": p_idx, "link": { "type": "content_ref", "label": pat.name, "target": { "module_code": module_code, "template_code": detail_template_code, "source_code": source_code, }, }, }) # Clinical values raw_manifestations = c_data.get("clinical_manifestations", []) clean_manifestations = [ str(m).strip() for m in raw_manifestations if str(m).strip() ] tongue = str(c_data.get("tongue", "")).strip() pulse = str(c_data.get("pulse", "")).strip() principle = c_data.get("treatment_principle", "") clean_principles = [ p.strip() for p in (principle if isinstance(principle, list) else [str(principle)]) if p.strip() ] raw_acu = c_data.get("acupuncture", {}) if isinstance(raw_acu, dict): acu_points = str(raw_acu.get("points", "")).strip() acu_method = str(raw_acu.get("method", "")).strip() else: acu_points = str(raw_acu).strip() acu_method = "" raw_exp = c_data.get("explanation", []) clean_exps = [str(e).strip() for e in raw_exp if str(e).strip()] # Item for master detail_patterns.json master_detail_items.append({ "code": source_code, "slug": f"{module_code}-ct0005-{source_code}", "name": pat.name, "title": f"{dis.name} - {pat.name}", "pattern_name": pat.name, "pattern_number": p_idx + 1, "condition": dis.name, "clinical_manifestations": clean_manifestations, "tongue": tongue, "pulse": pulse, "treatment_principle": clean_principles, "sort_order": global_pattern_sort, "acupuncture": { "points": acu_points, "method": acu_method, }, "explanation": clean_exps, }) global_pattern_sort += 1 # Embedded item for data.json point_list = [p.strip() for p in re.split(r"[,;]\s*", acu_points) if p.strip()] # Match points mentioned in each explanation sentence explanation_items = [] for exp in clean_exps: exp_lower = exp.lower() pts_in_exp = [pt for pt in point_list if pt.lower() in exp_lower] if not pts_in_exp and point_list: pts_in_exp = point_list[:1] explanation_items.append({ "points": pts_in_exp, "action": exp, }) embedded_patterns.append({ "category": cat.name, "pattern_name": pat.name, "clinical_manifestations": { "general": clean_manifestations, "tongue": tongue, "pulse": pulse, }, "treatment_principle": " ".join(clean_principles), "acupuncture": { "points": point_list, "method": acu_method, }, "explanation": explanation_items, "code": pat.pattern_code, }) dis_list_doc = {"contents": pat_list_items} dis_data_path = f"data/{cat.category_code}/{dis.disease_code}/list.json" files[dis_data_path] = json.dumps(dis_list_doc, indent=2) dis_full_doc = { "name": dis.name, "code": dis.disease_code, "title": dis.name, "definition": dis.overview or "", "contents": embedded_patterns, } files[f"data/{cat.category_code}/{dis.disease_code}/data.json"] = json.dumps( dis_full_doc, indent=2 ) content_mappings.append({ "name": f"{dis_slug}_list_content", "description": "", "code": dis_t_code, "data_path": dis_data_path, "template_path": f"templates/{dis_t_code}.json", }) # Insert master detail content mapping right after categories detail_data_path = "data/detail_patterns.json" files[detail_data_path] = json.dumps({"contents": master_detail_items}, indent=2) content_mappings.insert( len(categories) + 1, { "name": f"{module.slug.replace('-', '_')}_detail_content", "description": f"{module.name} detailed clinical pattern content", "code": detail_template_code, "data_path": detail_data_path, "template_path": f"templates/{detail_template_code}.json", }, ) # --------------------------------------------------------------------- # 9. Generate module.json & search_facets.json # --------------------------------------------------------------------- managed_by_val = getattr(module, "managed_by", "module_builder") module_doc = { "name": module.name, "description": module.description or f"TCM clinical therapeutics for {module.name}.", "short_description": module.short_description or module.name, "code": module.code, "kind": module.kind or "therapeutic", "managed_by": managed_by_val, "default_template_code": root_template_code, "metadata": { "version": "0.1", "status": "active" if module.is_active else "draft", "entry_template_code": root_template_code, "managed_by": managed_by_val, }, "content_mapping": content_mappings, } files["module.json"] = json.dumps(module_doc, indent=2) # Facets search_facets_doc = { "version": "1.0", "module_code": module_code, "facets": [ { "code": "category", "label": "Category", "category": "TCM Classification", "description": f"{module.name} category associated with the content", "control_type": "typeahead_multi", "allow_multiple_values": True, "value_source": "projected", "sort_order": 10, "mappings": [ { "template_code": cat_t_code, "attribute_key": f"{cat_t_code}.name", "content_kind": module.kind or "therapeutic", "mapping_strategy": "multivalue", } for cat_t_code in cat_template_codes.values() ], } ], } files["search_facets.json"] = json.dumps(search_facets_doc, indent=2) return module, files async def generate_zip_bundle(self, module_code: str) -> tuple[str, bytes]: module, files = await self.compile_module(module_code) folder_prefix = f"{module.code}-{module.slug}" buf = io.BytesIO() with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf: for rel_path, content in files.items(): archive_path = f"{folder_prefix}/{rel_path}" zf.writestr(archive_path, content) filename = f"{folder_prefix}.zip" return filename, buf.getvalue() async def sync_to_content_repo( self, module_code: str, repo_root: Path | None = None, ) -> dict[str, Any]: module, files = await self.compile_module(module_code) target_root = repo_root or DEFAULT_CONTENT_REPO_PATH if not target_root.exists(): raise HTTPException( status_code=500, detail=f"Content repository directory not found at: {target_root}", ) module_folder_name = f"{module.code}-{module.slug}" module_dir = target_root / module_folder_name # Safety Check: If folder already exists, verify it is managed by module_builder existing_module_json = module_dir / "module.json" if existing_module_json.exists(): try: existing_doc = json.loads(existing_module_json.read_text(encoding="utf-8")) existing_managed_by = existing_doc.get("managed_by") or existing_doc.get("metadata", {}).get("managed_by") if existing_managed_by != "module_builder": raise HTTPException( status_code=403, detail=( f"Safety Guard: Destination '{module_folder_name}' has an existing module.json " f"that is not managed by Module Builder (managed_by={existing_managed_by}). " "Aborting sync to protect legacy content." ), ) except json.JSONDecodeError: pass module_dir.mkdir(parents=True, exist_ok=True) files_written = 0 for rel_path, content in files.items(): file_path = module_dir / rel_path file_path.parent.mkdir(parents=True, exist_ok=True) file_path.write_text(content, encoding="utf-8") files_written += 1 # Update root config.json config_path = target_root / "config.json" config_updated = False if config_path.exists(): try: cfg = json.loads(config_path.read_text(encoding="utf-8")) modules_list = cfg.get("modules", []) existing_entry = next((m for m in modules_list if m.get("code") == module.code), None) entry_data = { "name": module.name, "code": module.code, "path": module_folder_name, "status": "active" if module.is_active else "draft", "sort_order": str(module.sort_order), } if existing_entry: existing_entry.update(entry_data) else: modules_list.append(entry_data) # Re-sort modules by integer sort_order def sort_key(m: dict[str, Any]) -> int: try: return int(m.get("sort_order", 99999)) except (ValueError, TypeError): return 99999 cfg["modules"] = sorted(modules_list, key=sort_key) config_path.write_text(json.dumps(cfg, indent=4), encoding="utf-8") config_updated = True except Exception as exc: logger.warning("Failed to update root config.json: %s", exc) return { "status": "synced", "module_code": module.code, "module_name": module.name, "target_dir": str(module_dir), "files_written": files_written, "config_updated": config_updated, "message": ( f"Successfully compiled and synced module '{module.name}' ({module.code}) " f"to {module_folder_name} ({files_written} files generated)." ), } # ========================================================================= # CONTRACT TEMPLATE GENERATORS # ========================================================================= def _create_list_template( self, *, module_code: str, template_code: str, template_name: str, is_searchable: bool = False, is_filterable: bool = False, ) -> dict[str, Any]: return { "name": template_name, "description": "", "code": template_code, "content_kind": "therapeutic", "is_searchable": is_searchable, "is_filterable": is_filterable, "attribute_prefix_code": template_code, "attribute_prefix_name": template_name, "attribute_defs": [ { "name": "Name", "code": "name", "data_type": "text", "default": "", }, { "name": "Code", "code": "code", "data_type": "text", "default": "", }, { "name": "Count", "code": "content_count", "data_type": "number", "default": 0, }, { "name": "Label", "code": "content_label", "data_type": "text", "default": "", }, { "name": "Sort Order", "code": "sort_order", "data_type": "number", "default": 0, }, { "name": "Content Link", "code": "link", "definition_kind": "object", "is_multivalue": False, "is_required": False, "is_searchable": False, "is_filterable": False, "children": [ { "name": "Type", "code": "type", "data_type": "text", "definition_kind": "scalar", "is_required": True, "default": "template_ref", "allowed_values": ["template_ref", "content_ref"], }, { "name": "Label", "code": "label", "data_type": "text", "definition_kind": "scalar", "is_required": False, }, { "name": "Target", "code": "target", "definition_kind": "object", "is_required": True, "children": [ { "name": "Module Code", "code": "module_code", "data_type": "text", "definition_kind": "scalar", "is_required": True, }, { "name": "Template Code", "code": "template_code", "data_type": "text", "definition_kind": "scalar", "is_required": True, }, { "name": "Source Code", "code": "source_code", "data_type": "text", "definition_kind": "scalar", "is_required": False, }, { "name": "Source Key", "code": "source_key", "data_type": "text", "definition_kind": "scalar", "is_required": False, }, { "name": "Content ID", "code": "content_id", "data_type": "text", "definition_kind": "scalar", "is_required": False, }, ], }, ], }, ], "presentation_contracts": [ { "client_type": "mobile", "version_no": 1, "is_active": True, "mode": "collection", "renderers": { "collection": "module_catalog_collection", "collection_item": "module_catalog_card", "detail": f"{template_code}_detail", }, "link": {"renderer": "content_link"}, "attributes": [ { "attribute_key": f"{template_code}.name", "empty_behavior": "hide", "visibility": "show", }, { "attribute_key": f"{template_code}.code", "empty_behavior": "hide", "visibility": "hide", }, { "attribute_key": f"{template_code}.content_count", "empty_behavior": "hide", "visibility": "show", }, { "attribute_key": f"{template_code}.content_label", "empty_behavior": "hide", "visibility": "show", }, { "attribute_key": f"{template_code}.sort_order", "empty_behavior": "hide", "visibility": "hide", }, { "attribute_key": f"{template_code}.link", "empty_behavior": "hide", "visibility": "hide", }, { "attribute_key": f"{template_code}.link.type", "empty_behavior": "hide", "visibility": "hide", }, { "attribute_key": f"{template_code}.link.label", "empty_behavior": "hide", "visibility": "hide", }, { "attribute_key": f"{template_code}.link.target", "empty_behavior": "hide", "visibility": "hide", }, { "attribute_key": f"{template_code}.link.target.module_code", "empty_behavior": "hide", "visibility": "hide", }, { "attribute_key": f"{template_code}.link.target.template_code", "empty_behavior": "hide", "visibility": "hide", }, { "attribute_key": f"{template_code}.link.target.source_code", "empty_behavior": "hide", "visibility": "hide", }, { "attribute_key": f"{template_code}.link.target.source_key", "empty_behavior": "hide", "visibility": "hide", }, { "attribute_key": f"{template_code}.link.target.content_id", "empty_behavior": "hide", "visibility": "hide", }, ], } ], "metadata": { "navigation_reference_policy": { "contract_version": "1.0", "default_reference_type": "template_ref", "allowed_reference_types": ["template_ref", "content_ref"], } }, } def _create_detail_template( self, *, module_code: str, template_code: str, ) -> dict[str, Any]: return { "name": "detail_content", "description": "", "code": template_code, "content_kind": "therapeutic", "is_searchable": False, "is_filterable": False, "attribute_prefix_code": template_code, "attribute_prefix_name": "detail_content", "attribute_defs": [ { "name": "Pattern Name", "code": "pattern_name", "data_type": "text", "default": "", }, { "name": "Code", "code": "code", "data_type": "text", "default": "", }, { "name": "Pattern Serial No", "code": "pattern_number", "data_type": "number", "default": 0, }, { "name": "Condition", "code": "condition", "data_type": "text", "default": "", }, { "name": "Clinical Manifestations", "code": "clinical_manifestations", "data_type": "text", "is_multivalue": True, "default": [], }, { "name": "Tongue", "code": "tongue", "data_type": "text", "default": "", }, { "name": "Pulse", "code": "pulse", "data_type": "text", "default": "", }, { "name": "Treatment Principle", "code": "treatment_principle", "data_type": "text", "is_multivalue": True, "default": [], }, { "name": "Sort Order", "code": "sort_order", "data_type": "number", "default": 0, }, { "name": "Acupuncture", "code": "acupuncture", "definition_kind": "object", "is_multivalue": False, "is_required": False, "is_searchable": False, "is_filterable": False, "children": [ { "name": "Points", "code": "points", "data_type": "text", "definition_kind": "scalar", "is_required": False, }, { "name": "Method", "code": "method", "data_type": "text", "definition_kind": "scalar", "is_required": False, }, ], }, { "name": "Explanation", "code": "explanation", "data_type": "text", "is_multivalue": True, "default": [], }, { "name": "Content Link", "code": "link", "definition_kind": "object", "is_multivalue": False, "is_required": False, "is_searchable": False, "is_filterable": False, "children": [ { "name": "Type", "code": "type", "data_type": "text", "definition_kind": "scalar", "is_required": True, "default": "template_ref", "allowed_values": ["template_ref", "content_ref"], }, { "name": "Label", "code": "label", "data_type": "text", "definition_kind": "scalar", "is_required": False, }, { "name": "Target", "code": "target", "definition_kind": "object", "is_required": True, "children": [ { "name": "Module Code", "code": "module_code", "data_type": "text", "definition_kind": "scalar", "is_required": True, }, { "name": "Template Code", "code": "template_code", "data_type": "text", "definition_kind": "scalar", "is_required": True, }, { "name": "Source Code", "code": "source_code", "data_type": "text", "definition_kind": "scalar", "is_required": False, }, { "name": "Source Key", "code": "source_key", "data_type": "text", "definition_kind": "scalar", "is_required": False, }, { "name": "Content ID", "code": "content_id", "data_type": "text", "definition_kind": "scalar", "is_required": False, }, ], }, ], }, ], "presentation_contracts": [ { "client_type": "mobile", "version_no": 1, "is_active": True, "mode": "collection", "renderers": { "collection": f"{template_code}_collection", "collection_item": f"{template_code}_card", "detail": f"{template_code}_detail", }, "link": {"renderer": "content_link"}, "attributes": [ { "attribute_key": f"{template_code}.condition", "empty_behavior": "hide", "visibility": "show", "display_order": 0, }, { "attribute_key": f"{template_code}.name", "empty_behavior": "hide", "visibility": "show", "display_order": 0, }, { "attribute_key": f"{template_code}.clinical_manifestations", "empty_behavior": "hide", "visibility": "show", "display_order": 0, }, { "attribute_key": f"{template_code}.tongue", "empty_behavior": "hide", "visibility": "show", "display_order": 0, }, { "attribute_key": f"{template_code}.pulse", "empty_behavior": "hide", "visibility": "show", "display_order": 0, }, { "attribute_key": f"{template_code}.treatment_principle", "empty_behavior": "hide", "visibility": "show", "display_order": 0, }, { "attribute_key": f"{template_code}.acupuncture", "empty_behavior": "hide", "visibility": "show", "display_order": 0, }, { "attribute_key": f"{template_code}.acupuncture.points", "empty_behavior": "hide", "visibility": "show", "display_order": 0, }, { "attribute_key": f"{template_code}.acupuncture.method", "empty_behavior": "hide", "visibility": "show", "display_order": 0, }, { "attribute_key": f"{template_code}.explanation", "empty_behavior": "hide", "visibility": "show", "display_order": 0, }, ], } ], "metadata": { "navigation_reference_policy": { "contract_version": "1.0", "default_reference_type": "template_ref", "allowed_reference_types": ["template_ref", "content_ref"], } }, }