HmiApiResource.java

package com.workbenchclassic.hmi;

import java.io.Reader;
import java.io.StringReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.SecurityContext;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/** HMI REST API. Identity is based on server-verified IMSAPI regLogin. */
@Path("/hmi/v1")
@Produces(MediaType.APPLICATION_JSON)
public class HmiApiResource {
    @Context private SecurityContext security;
    @Context private HttpServletRequest request;
    private static String schema() { return HmiDb.schemaPrefix(); }
    private static final String CSRF = "HMI_CSRF";
    private static final Set<String> WIDGET_TYPES = new HashSet<>();
    static {
        Collections.addAll(WIDGET_TYPES, "ui.text", "ui.table", "ui.button", "ui.header", "ui.image", "ui.script", "ui.curved-header", "ui.neon-actions", "ui.metal-panel", "mes.active-order",
                "mes.serial-scanner", "mes.station-status", "mes.booking-table", "mes.workplan",
                "wb.station-tree", "wb.station-config", "wb.workorders", "wb.history",
                "wb.activities", "wb.activity-designer", "wb.contacts", "wb.erp-groups",
                "wb.users", "wb.bom-import", "wb.part-import", "wb.station-import",
                "wb.erp-import", "wb.contact-import", "wb.user-import");
    }
    private String user() { return HmiAuth.user(request); }
    private boolean role(String name) { return HmiAuth.role(request,name); }
    private boolean designer() { return HmiAuth.designer(request); }
    private boolean publisher() { return HmiAuth.publisher(request); }
    private boolean admin() { return HmiAuth.admin(request); }
    private boolean scriptEditor() { return HmiAuth.scriptEditor(request); }
    private Response json(Object obj) { return Response.ok(obj instanceof String ? obj : obj.toString(), MediaType.APPLICATION_JSON).build(); }
    private Response err(int status, String msg) { return Response.status(status).type(MediaType.APPLICATION_JSON)
            .entity(new JSONObject().put("error", msg).toString()).build(); }
    private Response denied(boolean allowed) {
        if (user() == null) return err(401, "IMSAPI-Anmeldung erforderlich");
        if (!HmiSchemaBootstrap.isReady()) return err(503, "HMI schema not ready; check server logs");
        if (!allowed) return err(403, "Insufficient role");
        return null;
    }
    private boolean csrfValid() { return HmiAuth.csrf(request); }
    private Response writeAllowed(boolean allowed) {
        Response r = denied(allowed);
        return r != null ? r : (!csrfValid() ? err(403, "CSRF token missing or invalid") : null);
    }
    private static String stationKey(String station) {
        if (station == null || station.isEmpty()) return "*";
        if (!station.matches("[A-Za-z0-9_.-]{1,120}")) throw new JSONException("Invalid station number");
        return station;
    }
    private static String id() { return UUID.randomUUID().toString(); }
    private static JSONObject parse(String input) { return new JSONObject(input == null ? "{}" : input); }
    private static String need(JSONObject obj, String key, int max) {
        String s = obj.getString(key).trim();
        if (s.isEmpty() || s.length() > max) throw new JSONException("Invalid '" + key + "'");
        return s;
    }
    private static int bounded(JSONObject o, String k, int min, int max, int fallback) {
        int n = o.has(k) ? o.getInt(k) : fallback;
        if (n < min || n > max) throw new JSONException("Out of range: " + k);
        return n;
    }
    private static boolean legalKey(String s) { return s.matches("[A-Za-z0-9_.-]{1,120}"); }
    private static String clob(ResultSet rs, String col) throws SQLException {
        Reader reader = rs.getCharacterStream(col);
        if (reader == null) return null;
        try (Reader r = reader) {
            StringBuilder sb = new StringBuilder(); char[] buf = new char[4096]; int n;
            while ((n = r.read(buf)) != -1) { sb.append(buf, 0, n); if (sb.length() > 1000000) throw new SQLException("JSON too large"); }
            return sb.toString();
        } catch (java.io.IOException e) { throw new SQLException("Cannot read CLOB", e); }
    }
    private static void clob(PreparedStatement ps, int i, String text) throws SQLException {
        ps.setCharacterStream(i, new StringReader(text), text.length());
    }
    private static JSONObject objectOrEmpty(String value) { return value == null || value.trim().isEmpty() ? new JSONObject() : new JSONObject(value); }
    private static JSONObject validatePreferences(JSONObject input) {
        JSONObject out = new JSONObject();
        for (String key : input.keySet()) {
            switch (key) {
                case "fontScale": out.put(key, boundedScale(input.getDouble(key))); break;
                case "theme": { String s = input.getString(key); if (!s.equals("dark") && !s.equals("light") && !s.equals("system") && !s.equals("ios") && !s.equals("neon")) throw new JSONException("Invalid theme"); out.put(key, s); break; }
                case "contrast": { String s = input.getString(key); if (!s.equals("normal") && !s.equals("high")) throw new JSONException("Invalid contrast"); out.put(key, s); break; }
                case "accent": { String s = input.getString(key); if (!s.matches("#[0-9a-fA-F]{6}")) throw new JSONException("Invalid accent color"); out.put(key, s); break; }
                default: throw new JSONException("Unknown preference: " + key);
            }
        }
        return out;
    }
    private static double boundedScale(double x) { if (!Double.isFinite(x) || x < 0.75 || x > 2.0) throw new JSONException("fontScale must be 0.75 to 2.0"); return x; }
    private static JSONObject validateTemplate(JSONObject layout) {
        JSONArray widgets = layout.getJSONArray("widgets");
        if (widgets.length() > 80) throw new JSONException("Maximum 80 widgets");
        Set<String> ids = new HashSet<>();
        JSONObject cleaned = new JSONObject(); JSONArray out = new JSONArray();
        for (int i = 0; i < widgets.length(); i++) {
            JSONObject w = widgets.getJSONObject(i);
            String widgetId = need(w, "id", 120); String type = need(w, "type", 100);
            if (!legalKey(widgetId) || !WIDGET_TYPES.contains(type) || !ids.add(widgetId)) throw new JSONException("Invalid or duplicate widget ID/type");
            if ("ui.script".equals(type)) {
                JSONObject properties = w.optJSONObject("props");
                Object source = properties == null ? "" : properties.opt("script");
                if (source != null && !(source instanceof String)) throw new JSONException("JavaScript must be text");
                if (source instanceof String && ((String) source).length() > 8000)
                    throw new JSONException("JavaScript limited to 8000 characters");
            }
            JSONObject item = new JSONObject().put("id", widgetId).put("type", type)
                .put("x", bounded(w,"x",0,11,0)).put("y",bounded(w,"y",0,200,0))
                .put("w",bounded(w,"w",1,12,4)).put("h",bounded(w,"h",1,20,3))
                .put("mandatory",w.optBoolean("mandatory",false)).put("personalizable",w.optBoolean("personalizable",true))
                .put("visibleToRoles",validWidgetRoles(w.optJSONArray("visibleToRoles")))
                .put("props",w.optJSONObject("props") == null ? new JSONObject() : w.getJSONObject("props"));
            if (item.optBoolean("mandatory") && item.getJSONArray("visibleToRoles").length() > 0)
                throw new JSONException("Mandatory widgets cannot be restricted to specific roles");
            if (item.getInt("x") + item.getInt("w") > 12) throw new JSONException("Widget exceeds grid width");
            if (item.toString().length() > 16000) throw new JSONException("Widget props too large");
            out.put(item);
        }
        cleaned.put("widgets", out);
        return cleaned;
    }
    /** The server, not Vue, decides whether JavaScript content was added or changed. */
    private static java.util.Map<String,String> scripts(JSONObject layout) {
        java.util.Map<String,String> map = new java.util.HashMap<>();
        JSONArray items = layout.optJSONArray("widgets");
        if (items == null) return map;
        for (int n=0; n<items.length(); n++) {
            JSONObject item = items.getJSONObject(n);
            if ("ui.script".equals(item.optString("type"))) {
                JSONObject props = item.optJSONObject("props");
                map.put(item.getString("id"), props == null ? "" : props.optString("script", ""));
            }
        }
        return map;
    }
    private static boolean scriptChanges(JSONObject previous, JSONObject proposed) {
        return !scripts(previous).equals(scripts(proposed));
    }

    private static JSONArray validWidgetRoles(JSONArray roles) {
        JSONArray out = new JSONArray();
        if (roles == null) return out;
        if (roles.length() > 30) throw new JSONException("Too many widget roles");
        java.util.Set<String> seen = new java.util.HashSet<>();
        for (int i=0;i<roles.length();i++) {
            String role = roles.getString(i);
            if (!legalKey(role) || !seen.add(role)) throw new JSONException("Invalid widget role");
            out.put(role);
        }
        return out;
    }
    private static JSONObject validateOverrides(JSONObject override) {
        JSONObject out = new JSONObject();
        if (override.keySet().size() > 80) throw new JSONException("Too many overrides");
        for (String id : override.keySet()) {
            if (!legalKey(id)) throw new JSONException("Invalid widget ID");
            JSONObject p = override.getJSONObject(id);
            for (String k : p.keySet()) if (!k.equals("x") && !k.equals("y") && !k.equals("w") && !k.equals("h") && !k.equals("hidden")) throw new JSONException("Forbidden override");
            JSONObject o = new JSONObject()
                .put("x", bounded(p,"x",0,11,0)).put("y",bounded(p,"y",0,200,0))
                .put("w",bounded(p,"w",1,12,4)).put("h",bounded(p,"h",1,20,3))
                .put("hidden",p.optBoolean("hidden",false));
            if (o.getInt("x") + o.getInt("w") > 12) throw new JSONException("Widget exceeds width");
            out.put(id,o);
        }
        return out;
    }
    /** Requires a GlassFish administrator role; tests dsCustNJTA LIVE and returns safe metadata. */
    @GET @Path("diagnostics")
    public Response diagnostics() {
        if (user() == null) return err(401, "IMSAPI-Anmeldung erforderlich");
        if (!admin()) return err(403, "hmi-admin role required");
        JSONObject out = new JSONObject()
            .put("user", user())
            .put("readyAtDeployment", HmiSchemaBootstrap.isReady())
            .put("initializationPhase", HmiSchemaBootstrap.phase())
            .put("failureCode", HmiSchemaBootstrap.failureCode())
            .put("pool", "dsCustNJTA");
        try (Connection c = HmiDb.open()) {
            String db = c.getMetaData().getDatabaseProductName();
            boolean oracle = db.toLowerCase(java.util.Locale.ROOT).contains("oracle");
            boolean sqlServer = db.toLowerCase(java.util.Locale.ROOT).contains("sql server");
            out.put("poolReachableNow", true).put("database", oracle ? "ORACLE" : sqlServer ? "SQL_SERVER" : "UNKNOWN")
                .put("schema", oracle ? "CUST" : "cust");
            try (PreparedStatement p = c.prepareStatement(oracle ? "SELECT 1 FROM DUAL" : "SELECT 1");
                 ResultSet rs = p.executeQuery()) {
                out.put("connectionQueryOk", rs.next() && rs.getInt(1) == 1);
            }
            int found = 0;
            String[] tables = {"HMI_APP_PAGE", "HMI_APP_LAYOUT", "HMI_APP_PREF", "HMI_APP_CSS_REVISION", "HMI_APP_SCHEMA_VERSION"};
            for (String t : tables) {
                try (ResultSet rs = c.getMetaData().getTables(null, oracle ? "CUST" : "cust", t, new String[]{"TABLE"})) {
                    if (rs.next()) found++;
                }
            }
            out.put("tablesFound", found).put("tablesExpected", tables.length);
            return json(out);
        } catch (SQLException e) {
            java.util.logging.Logger.getLogger(HmiApiResource.class.getName())
                .log(java.util.logging.Level.WARNING, "Authenticated HMI diagnostics failed", e);
            return json(out.put("poolReachableNow", false).put("connectionQueryOk", false).put("failure", "CHECK_GLASSFISH_LOG"));
        }
    }

    @GET @Path("status")
    public Response status() { Response r = denied(admin()); return r != null ? r : json(new JSONObject().put("ready",true).put("detail",HmiSchemaBootstrap.state())); }
    @GET @Path("widgets")
    public Response widgets() { Response r = denied(true); if (r!=null) return r;
        JSONArray a = new JSONArray();
        for (String t : WIDGET_TYPES) a.put(new JSONObject().put("type",t).put("name",t.replace("mes.", "MES: ").replace("ui.", "UI: ")));
        return json(a);
    }
    @GET @Path("roles")
    public Response viewableRoleNames() {
        Response r=denied(designer()); if(r!=null)return r;
        JSONArray out=new JSONArray(); java.util.Set<String> seen=new java.util.TreeSet<>();
        java.util.Collections.addAll(seen,"hmi-admin","hmi-designer","hmi-publisher","hmi-script-editor");
        try(Connection c=HmiDb.open();PreparedStatement p=c.prepareStatement(
                "SELECT ROLE_KEY FROM "+schema()+"HMI_APP_ROLE ORDER BY ROLE_KEY");ResultSet rs=p.executeQuery()) {
            while(rs.next())seen.add(rs.getString(1));
            for(String name:seen)out.put(new JSONObject().put("key",name).put("description",name));
            return json(out);
        }catch(SQLException e){return dbError(e);}
    }
    /** A hidden parent also hides the complete subtree for normal operators. */
    private static boolean visiblePage(String pageId, java.util.Map<String,JSONObject> byId) {
        java.util.Set<String> seen=new java.util.HashSet<>();
        String current=pageId;
        while(current!=null) {
            if(!seen.add(current))return false;
            JSONObject page=byId.get(current);
            if(page==null || !page.getBoolean("enabled"))return false;
            current=page.isNull("parentPageId")?null:page.optString("parentPageId",null);
        }
        return true;
    }
    @GET @Path("pages")
    public Response pages() {
        Response r = denied(true); if (r!=null) return r;
        JSONArray out = new JSONArray();
        java.util.Map<String,JSONObject> found=new java.util.LinkedHashMap<>();
        try(Connection c=HmiDb.open();PreparedStatement ps=c.prepareStatement(
            "SELECT ID,PAGE_KEY,TITLE,MENU_GROUP,SORT_ORDER,ENABLED,PARENT_PAGE_ID FROM " + schema() + "HMI_APP_PAGE ORDER BY SORT_ORDER,TITLE");
            ResultSet rs=ps.executeQuery()) {
            while(rs.next()) {
                String parent=rs.getString(7);
                JSONObject page=new JSONObject().put("id",rs.getString(1)).put("key",rs.getString(2)).put("title",rs.getString(3))
                    .put("menuGroup",rs.getString(4)).put("order",rs.getInt(5)).put("enabled",rs.getInt(6)==1)
                    .put("parentPageId",parent==null?JSONObject.NULL:parent);
                found.put(page.getString("id"),page);
            }
            for(JSONObject page:found.values()) if(designer()||visiblePage(page.getString("id"),found))out.put(page);
            return json(out);
        }catch(SQLException e){return dbError(e);}
    }
    /** Parent references are validated server-side to prevent broken or cyclic navigation. */
    private static String parentId(JSONObject input) {
        if (input.isNull("parentPageId") || !input.has("parentPageId")) return null;
        String value = input.getString("parentPageId").trim();
        if (value.isEmpty()) return null;
        if (!legalKey(value)) throw new JSONException("Invalid parentPageId");
        return value;
    }
    private static String pageMenu(JSONObject input) {
        String menu = input.optString("menuGroup", "Allgemein").trim();
        if (menu.isEmpty() || menu.length() > 120 || menu.indexOf('/') >= 0)
            throw new JSONException("Invalid root menu name");
        return menu;
    }
    private static String parentMenu(Connection c, String parentId) throws SQLException {
        try (PreparedStatement ps=c.prepareStatement("SELECT MENU_GROUP FROM " + schema() + "HMI_APP_PAGE WHERE ID=?")) {
            ps.setString(1,parentId);
            try (ResultSet rs=ps.executeQuery()) {
                return rs.next() ? rs.getString(1) : null;
            }
        }
    }
    private static String parentOf(Connection c, String id) throws SQLException {
        try (PreparedStatement ps=c.prepareStatement("SELECT PARENT_PAGE_ID FROM " + schema() + "HMI_APP_PAGE WHERE ID=?")) {
            ps.setString(1,id);
            try (ResultSet rs=ps.executeQuery()) {
                return rs.next() ? rs.getString(1) : null;
            }
        }
    }
    private static void validatePageParent(Connection c, String currentId, String parent) throws SQLException {
        if (parent == null) return;
        java.util.Set<String> visited = new java.util.HashSet<>();
        String candidate = parent;
        for (int depth=0;candidate!=null;depth++) {
            if (depth > 32 || !visited.add(candidate) || candidate.equals(currentId))
                throw new JSONException("Navigation cycle or depth limit detected");
            if (parentMenu(c,candidate)==null)
                throw new JSONException("Parent page not found");
            candidate = parentOf(c,candidate);
        }
    }
    /** Propagate the root-menu name through all descendants when a page changes group. */
    private static void updateDescendantMenus(Connection c, String rootId, String menu) throws SQLException {
        java.util.Set<String> seen = new java.util.HashSet<>();
        java.util.ArrayDeque<String> pending = new java.util.ArrayDeque<>();
        pending.add(rootId);seen.add(rootId);
        while (!pending.isEmpty()) {
            String current=pending.remove();
            try(PreparedStatement ps=c.prepareStatement("SELECT ID FROM " + schema() + "HMI_APP_PAGE WHERE PARENT_PAGE_ID=?")) {
                ps.setString(1,current);
                try(ResultSet rs=ps.executeQuery()) {
                    while(rs.next()) {
                        String child=rs.getString(1);
                        if (!seen.add(child)) throw new SQLException("Navigation cycle in stored page tree");
                        if (seen.size()>1000) throw new SQLException("Too many navigation pages");
                        pending.add(child);
                    }
                }
            }
            if(!current.equals(rootId)) {
                try(PreparedStatement ps=c.prepareStatement("UPDATE " + schema() + "HMI_APP_PAGE SET MENU_GROUP=? WHERE ID=?")) {
                    ps.setString(1,menu);ps.setString(2,current);ps.executeUpdate();
                }
            }
        }
    }
    @POST @Path("pages") @Consumes(MediaType.APPLICATION_JSON)
    public Response createPage(String body) {
        Response r=writeAllowed(designer()); if(r!=null)return r;
        try {
            JSONObject input=parse(body);
            String key=need(input,"key",120); if(!legalKey(key)) return err(400,"Invalid page key");
            String title=need(input,"title",255), pageId=id();
            String menu=pageMenu(input), parent=parentId(input);
            int order=bounded(input,"order",0,100000,0);
            try (Connection c=HmiDb.open()) {
                c.setAutoCommit(false);
                try {
                    validatePageParent(c,pageId,parent);
                    if(parent!=null)menu=parentMenu(c,parent);
                    try (PreparedStatement ps=c.prepareStatement(
                        "INSERT INTO "+schema()+"HMI_APP_PAGE(ID,PAGE_KEY,TITLE,MENU_GROUP,SORT_ORDER,ENABLED,PARENT_PAGE_ID) VALUES (?,?,?,?,?,1,?)")) {
                        ps.setString(1,pageId);ps.setString(2,key);ps.setString(3,title);
                        ps.setString(4,menu);ps.setInt(5,order);ps.setString(6,parent);ps.executeUpdate();
                    }
                    audit(c,"page.created",pageId,key);c.commit();
                } catch (Exception ex) {c.rollback();throw ex;}
            }
            return json(new JSONObject().put("id",pageId).put("key",key));
        } catch (JSONException e) { return err(400,e.getMessage()); } catch (SQLException e) { return dbError(e); }
          catch (Exception e) { return err(400,"Cannot create page"); }
    }
    @PUT @Path("pages/{pageId}") @Consumes(MediaType.APPLICATION_JSON)
    public Response updatePage(@PathParam("pageId") String pageId, String body) {
        Response r=writeAllowed(designer()); if(r!=null)return r;
        try {
            JSONObject input=parse(body);
            String title=need(input,"title",255), menu=pageMenu(input), parent=parentId(input);
            int order=bounded(input,"order",0,100000,0);
            boolean enabled=input.optBoolean("enabled",true);
            try(Connection c=HmiDb.open()) {
                c.setAutoCommit(false);
                try {
                    if (!pageExists(c,pageId)) {c.rollback();return err(404,"Page not found");}
                    validatePageParent(c,pageId,parent);
                    if(parent!=null)menu=parentMenu(c,parent);
                    try(PreparedStatement ps=c.prepareStatement(
                        "UPDATE "+schema()+"HMI_APP_PAGE SET TITLE=?,MENU_GROUP=?,SORT_ORDER=?,ENABLED=?,PARENT_PAGE_ID=? WHERE ID=?")) {
                        ps.setString(1,title);ps.setString(2,menu);ps.setInt(3,order);
                        ps.setInt(4,enabled?1:0);ps.setString(5,parent);ps.setString(6,pageId);
                        ps.executeUpdate();
                    }
                    updateDescendantMenus(c,pageId,menu);
                    audit(c,"page.updated",pageId,title);c.commit();
                }catch(Exception ex){c.rollback();throw ex;}
            }
            return json(new JSONObject().put("ok",true));
        } catch (JSONException e) { return err(400,e.getMessage()); } catch (SQLException e) { return dbError(e); }
          catch (Exception e) { return err(400,"Cannot update page"); }
    }
    /** Rename a root menu without changing individual pages' parent relationships. */
    @PUT @Path("navigation/root") @Consumes(MediaType.APPLICATION_JSON)
    public Response renameRootMenu(String body) {
        Response r=writeAllowed(designer());if(r!=null)return r;
        try {
            JSONObject input=parse(body);
            String previous=need(input,"previous",120), next=need(input,"next",120);
            if(!next.equals(pageMenu(new JSONObject().put("menuGroup",next))))return err(400,"Invalid menu");
            try(Connection c=HmiDb.open();PreparedStatement ps=c.prepareStatement(
                "UPDATE "+schema()+"HMI_APP_PAGE SET MENU_GROUP=? WHERE MENU_GROUP=?")) {
                ps.setString(1,next);ps.setString(2,previous);
                int count=ps.executeUpdate();
                if(count==0)return err(404,"Root menu not found");
                audit(c,"root.renamed",previous,next);
                return json(new JSONObject().put("updatedPages",count));
            }
        }catch(JSONException e){return err(400,e.getMessage());}catch(SQLException e){return dbError(e);}
    }
    @GET @Path("pages/{pageId}/templates")
    public Response templates(@PathParam("pageId")String pageId) {
        Response r=denied(designer());if(r!=null)return r;
        JSONArray a=new JSONArray();
        try (Connection c=HmiDb.open();PreparedStatement p=c.prepareStatement("SELECT ID,VERSION_NO,STATUS,UPDATED_BY FROM "+schema()+"HMI_APP_TEMPLATE WHERE PAGE_ID=? ORDER BY VERSION_NO DESC")) {
            p.setString(1,pageId);try(ResultSet rs=p.executeQuery()){while(rs.next())a.put(new JSONObject().put("id",rs.getString(1)).put("version",rs.getInt(2)).put("status",rs.getString(3)).put("author",rs.getString(4)));}
            return json(a);
        }catch(SQLException e){return dbError(e);}
    }
    @POST @Path("pages/{pageId}/templates") @Consumes(MediaType.APPLICATION_JSON)
    public Response createTemplate(@PathParam("pageId") String pageId,String body) {
        Response r=writeAllowed(designer());if(r!=null)return r;
        try {
            JSONObject layout=validateTemplate(parse(body));
            if (!scriptEditor() && !scripts(layout).isEmpty())
                return err(403, "Zum Hinzufügen von JavaScript-Widgets ist hmi-script-editor erforderlich");
            try(Connection c=HmiDb.open()) {
                if(!pageExists(c,pageId))return err(404,"Page not found");
                int version=1;
                try(PreparedStatement p=c.prepareStatement("SELECT MAX(VERSION_NO) FROM "+schema()+"HMI_APP_TEMPLATE WHERE PAGE_ID=?")){
                    p.setString(1,pageId);try(ResultSet rs=p.executeQuery()){if(rs.next())version=rs.getInt(1)+1;}
                }
                String templateId=id();
                try(PreparedStatement p=c.prepareStatement("INSERT INTO "+schema()+"HMI_APP_TEMPLATE(ID,PAGE_ID,VERSION_NO,STATUS,LAYOUT_JSON,UPDATED_BY,UPDATED_AT) VALUES (?,?,?,?,?,?,?)")) {
                    p.setString(1,templateId);p.setString(2,pageId);p.setInt(3,version);p.setString(4,"DRAFT");clob(p,5,layout.toString());
                    p.setString(6,user());p.setTimestamp(7,Timestamp.from(Instant.now()));p.executeUpdate();
                }
                audit(c,"template.created",templateId,pageId);
                return json(new JSONObject().put("id",templateId).put("version",version).put("status","DRAFT"));
            }
        } catch(JSONException e){return err(400,e.getMessage());}catch(SQLException e){return dbError(e);}
    }
    @PUT @Path("templates/{templateId}") @Consumes(MediaType.APPLICATION_JSON)
    public Response saveTemplate(@PathParam("templateId")String templateId,String body){
        Response r=writeAllowed(designer());if(r!=null)return r;
        try {
            JSONObject layout=validateTemplate(parse(body));
            try(Connection c=HmiDb.open()) {
                c.setAutoCommit(false);
                try {
                    String current = null;
                    // Lock the draft while comparing its scripts and persisting the new version.
                    boolean oracle = HmiDb.isOracle();
                    String sql = oracle
                        ? "SELECT LAYOUT_JSON FROM "+schema()+"HMI_APP_TEMPLATE WHERE ID=? AND STATUS='DRAFT' FOR UPDATE"
                        : "SELECT LAYOUT_JSON FROM "+schema()+"HMI_APP_TEMPLATE WITH (UPDLOCK, ROWLOCK) WHERE ID=? AND STATUS='DRAFT'";
                    try(PreparedStatement locked=c.prepareStatement(sql)) {
                        locked.setString(1,templateId);
                        try(ResultSet rs=locked.executeQuery()) {
                            if(rs.next())current=clob(rs,"LAYOUT_JSON");
                        }
                    }
                    if(current==null) { c.rollback();return err(409,"Template not a draft or not found"); }
                    if (!scriptEditor() && scriptChanges(objectOrEmpty(current),layout)) {
                        c.rollback();return err(403,"JavaScript-Änderungen benötigen die Rolle hmi-script-editor");
                    }
                    try(PreparedStatement p=c.prepareStatement("UPDATE "+schema()+"HMI_APP_TEMPLATE SET LAYOUT_JSON=?,UPDATED_BY=?,UPDATED_AT=? WHERE ID=? AND STATUS='DRAFT'")) {
                        clob(p,1,layout.toString());p.setString(2,user());p.setTimestamp(3,Timestamp.from(Instant.now()));p.setString(4,templateId);
                        if(p.executeUpdate()==0) {c.rollback();return err(409,"Template not a draft or not found");}
                    }
                    audit(c,"template.saved",templateId,"");
                    if(scriptChanges(objectOrEmpty(current),layout))audit(c,"widget.script.edited",templateId,"JavaScript code updated");
                    c.commit();
                } catch(SQLException | RuntimeException ex) {c.rollback();throw ex;}
            }
            return json(new JSONObject().put("ok",true));
        }catch(JSONException e){return err(400,e.getMessage());}catch(SQLException e){return dbError(e);}
    }
    @GET @Path("templates/{templateId}")
    public Response getTemplate(@PathParam("templateId")String templateId) {
        Response r=denied(designer());if(r!=null)return r;
        try(Connection c=HmiDb.open();PreparedStatement p=c.prepareStatement("SELECT ID,PAGE_ID,VERSION_NO,STATUS,LAYOUT_JSON FROM "+schema()+"HMI_APP_TEMPLATE WHERE ID=?")){
            p.setString(1,templateId);try(ResultSet rs=p.executeQuery()){
                if(!rs.next())return err(404,"Template not found");
                return json(new JSONObject().put("id",rs.getString(1)).put("pageId",rs.getString(2))
                     .put("version",rs.getInt(3)).put("status",rs.getString(4))
                     .put("layout",objectOrEmpty(clob(rs,"LAYOUT_JSON"))));
            }
        }catch(SQLException e){return dbError(e);}
    }
    @POST @Path("templates/{templateId}/archive")
    public Response archive(@PathParam("templateId")String templateId) {
        Response r=writeAllowed(publisher());if(r!=null)return r;
        try(Connection c=HmiDb.open()) {
            try(PreparedStatement chk=c.prepareStatement("SELECT ID FROM "+schema()+"HMI_APP_ASSIGNMENT WHERE TEMPLATE_ID=?")) {
                chk.setString(1,templateId);try(ResultSet rs=chk.executeQuery()){if(rs.next())return err(409,"Template is assigned; update assignments before archiving");}
            }
            try(PreparedStatement p=c.prepareStatement("UPDATE "+schema()+"HMI_APP_TEMPLATE SET STATUS='ARCHIVED' WHERE ID=? AND STATUS='PUBLISHED'")) {
                p.setString(1,templateId);if(p.executeUpdate()!=1)return err(409,"Not published or not found");
            }
            audit(c,"template.archived",templateId,"");return json(new JSONObject().put("ok",true));
        }catch(SQLException e){return dbError(e);}
    }
    @POST @Path("templates/{templateId}/publish")
    public Response publish(@PathParam("templateId")String templateId) {
        Response r=writeAllowed(publisher());if(r!=null)return r;
        try(Connection c=HmiDb.open()) {
            c.setAutoCommit(false);
            try {
                String pageId;
                try(PreparedStatement p=c.prepareStatement("SELECT PAGE_ID,STATUS FROM "+schema()+"HMI_APP_TEMPLATE WHERE ID=?")) {
                    p.setString(1,templateId);
                    try(ResultSet rs=p.executeQuery()){
                        if(!rs.next()){c.rollback();return err(404,"Template not found");}
                        pageId=rs.getString(1);
                        if(!"DRAFT".equals(rs.getString(2))){c.rollback();return err(409,"Only drafts can be published");}
                    }
                }
                // Keep other published templates available for group/station assignments.
                // Default page resolves highest published version; explicit assignment stays pinned.
                try(PreparedStatement p=c.prepareStatement("UPDATE "+schema()+"HMI_APP_TEMPLATE SET STATUS='PUBLISHED' WHERE ID=? AND STATUS='DRAFT'")){
                    p.setString(1,templateId);if(p.executeUpdate()!=1)throw new SQLException("Concurrent template publication");
                }
                audit(c,"template.published",templateId,pageId);c.commit();
                return json(new JSONObject().put("ok",true));
            }catch(Exception ex){c.rollback();throw ex;}
        }catch(Exception e){return dbError(e);}
    }
    @GET @Path("pages/{pageId}/effective")
    public Response effective(@PathParam("pageId")String pageId,@QueryParam("station")String station){
        Response r=denied(true);if(r!=null)return r;
        try(Connection c=HmiDb.open()){
            JSONObject page=fetchPage(c,pageId);
            if(page==null)return err(404,"Page not found");
            if(!designer()){
                java.util.Set<String> seen=new java.util.HashSet<>();
                JSONObject ancestor=page;
                while(ancestor!=null){
                    if(!seen.add(ancestor.getString("id"))||!ancestor.getBoolean("enabled"))return err(404,"Page not found");
                    String parent=ancestor.isNull("parentPageId")?null:ancestor.optString("parentPageId",null);
                    ancestor=parent==null?null:fetchPage(c,parent);
                    if(parent!=null&&ancestor==null)return err(404,"Page not found");
                }
            }
            List<String> groups=groups(c,user());
            JSONObject template=resolveTemplate(c,pageId,station,groups);
            if(template==null)return err(404,"No published template assigned");
            JSONObject prefs=new JSONObject().put("fontScale",1).put("theme","ios").put("contrast","normal").put("accent","#a40640");
            merge(prefs,preference(c,"DEFAULT","*"));
            for(String g:groups)merge(prefs,preference(c,"GROUP",g));
            if(station!=null&&!station.isEmpty())merge(prefs,preference(c,"STATION",station));
            merge(prefs,preference(c,"USER",user()));
            JSONObject overrides=new JSONObject();String baseId="";
            try(PreparedStatement p=c.prepareStatement("SELECT BASE_TEMPLATE_ID,OVERRIDES_JSON FROM "+schema()+"HMI_APP_LAYOUT WHERE USER_ID=? AND PAGE_ID=? AND STATION_ID=?")){
                p.setString(1,user());p.setString(2,pageId);p.setString(3, stationKey(station));
                try(ResultSet rs=p.executeQuery()) {if(rs.next()){baseId=rs.getString(1);overrides=objectOrEmpty(clob(rs,"OVERRIDES_JSON"));}}
            }
            JSONObject layout=template.getJSONObject("layout");
            JSONArray effectiveWidgets=new JSONArray();
            java.util.Set<String> granted = HmiAuth.roles(request);
            for(Object val:layout.getJSONArray("widgets")) {
                JSONObject widget=new JSONObject(val.toString());String widgetId=widget.getString("id");
                // Security: role-restricted widgets must never be delivered in the effective payload.
                JSONArray required = widget.optJSONArray("visibleToRoles");
                if (required!=null && required.length()>0 && !granted.contains("hmi-admin")) {
                    boolean allowed=false;
                    for(int i=0;i<required.length();i++) if(granted.contains(required.optString(i))) {allowed=true;break;}
                    if(!allowed)continue;
                }
                if(widget.optBoolean("personalizable",true)&&overrides.has(widgetId)){
                    JSONObject o=overrides.getJSONObject(widgetId);
                    for(String key:new String[]{"x","y","w","h"})if(o.has(key))widget.put(key,o.getInt(key));
                    if(!widget.optBoolean("mandatory",false)&&o.optBoolean("hidden",false))widget.put("hidden",true);
                    if(widget.getInt("x")+widget.getInt("w")>12)widget.put("x",0);
                }
                effectiveWidgets.put(widget);
            }
            return json(new JSONObject().put("page",page).put("templateId",template.getString("id"))
                .put("version",template.getInt("version")).put("originalTemplateId",baseId)
                .put("layout",new JSONObject().put("widgets",effectiveWidgets)).put("preferences",prefs));
        }catch(Exception e){return dbError(e);}
    }
    @PUT @Path("pages/{pageId}/layout") @Consumes(MediaType.APPLICATION_JSON)
    public Response saveLayout(@PathParam("pageId")String pageId,String body){
        Response r=writeAllowed(true);if(r!=null)return r;
        try {
            JSONObject in=parse(body);
            JSONObject o=validateOverrides(in.getJSONObject("overrides"));
            try(Connection c=HmiDb.open()){
                if(!pageExists(c,pageId))return err(404,"Page not found");
                // Server enforcement: only published, personalizable widget IDs can be overridden.
                JSONObject template=resolveTemplate(c,pageId,in.optString("station",""),groups(c,user()));
                if(template==null)return err(409,"Page has no published template");
                JSONObject allowed=new JSONObject();
                for(Object obj:template.getJSONObject("layout").getJSONArray("widgets")) {
                    JSONObject w=(JSONObject)obj;String widgetId=w.getString("id");
                    if(!o.has(widgetId) || !w.optBoolean("personalizable",true))continue;
                    JSONObject override=o.getJSONObject(widgetId);
                    if(w.optBoolean("mandatory",false)&&override.optBoolean("hidden",false))return err(400,"Cannot hide mandatory widget");
                    allowed.put(widgetId,override);
                }
                int count;
                try(PreparedStatement p=c.prepareStatement("UPDATE "+schema()+"HMI_APP_LAYOUT SET OVERRIDES_JSON=?,BASE_TEMPLATE_ID=?,UPDATED_AT=? WHERE USER_ID=? AND PAGE_ID=? AND STATION_ID=?")){
                    clob(p,1,allowed.toString());p.setString(2,template.getString("id"));p.setTimestamp(3,Timestamp.from(Instant.now()));p.setString(4,user());p.setString(5,pageId);p.setString(6,stationKey(in.optString("station", "")));count=p.executeUpdate();
                }
                if(count==0){try(PreparedStatement p=c.prepareStatement("INSERT INTO "+schema()+"HMI_APP_LAYOUT(USER_ID,PAGE_ID,STATION_ID,BASE_TEMPLATE_ID,OVERRIDES_JSON,UPDATED_AT) VALUES(?,?,?,?,?,?)")){
                    p.setString(1,user());p.setString(2,pageId);p.setString(3,stationKey(in.optString("station", "")));p.setString(4,template.getString("id"));clob(p,5,allowed.toString());p.setTimestamp(6,Timestamp.from(Instant.now()));p.executeUpdate();
                }}
                audit(c,"user.layout",pageId,"Saved overrides");
                return json(new JSONObject().put("ok",true).put("saved",allowed.length()));
            }
        }catch(JSONException e){return err(400,e.getMessage());}catch(SQLException e){return dbError(e);}
    }
    @GET @Path("preferences")
    public Response myPreferences(){Response r=denied(true);if(r!=null)return r;
        try(Connection c=HmiDb.open()){return json(preference(c,"USER",user()));}catch(SQLException e){return dbError(e);}}
    @PUT @Path("preferences") @Consumes(MediaType.APPLICATION_JSON)
    public Response myPreferencesSave(String body){Response r=writeAllowed(true);if(r!=null)return r;
        try{return storePreferences("USER",user(),parse(body));}catch(JSONException e){return err(400,e.getMessage());}}
    @PUT @Path("groups/{group}/preferences") @Consumes(MediaType.APPLICATION_JSON)
    public Response groupPreferences(@PathParam("group")String group,String body){Response r=writeAllowed(admin());if(r!=null)return r;
        if(!legalKey(group))return err(400,"Invalid group");
        try{return storePreferences("GROUP",group,parse(body));}catch(JSONException e){return err(400,e.getMessage());}}
    @PUT @Path("groups/{group}/members/{member}")
    public Response groupMember(@PathParam("group")String group,@PathParam("member")String member){
        Response r=writeAllowed(admin());if(r!=null)return r;
        if(!legalKey(group)||member.length()>255||member.isEmpty())return err(400,"Invalid group or member");
        try(Connection c=HmiDb.open()){
            try(PreparedStatement p=c.prepareStatement("SELECT USER_ID FROM "+schema()+"HMI_APP_GROUP_MEMBER WHERE GROUP_ID=? AND USER_ID=?")){
                p.setString(1,group);p.setString(2,member);try(ResultSet rs=p.executeQuery()){if(rs.next())return json(new JSONObject().put("ok",true));}
            }
            try(PreparedStatement p=c.prepareStatement("INSERT INTO "+schema()+"HMI_APP_GROUP_MEMBER(USER_ID,GROUP_ID) VALUES (?,?)")){
                p.setString(1,member);p.setString(2,group);p.executeUpdate();
            }
            audit(c,"group.member.added",group,member);return json(new JSONObject().put("ok",true));
        }catch(SQLException e){return dbError(e);}
    }
    @POST @Path("assignments") @Consumes(MediaType.APPLICATION_JSON)
    public Response assign(String body){Response r=writeAllowed(publisher());if(r!=null)return r;
        try{
            JSONObject in=parse(body);String pageId=need(in,"pageId",64), templateId=need(in,"templateId",64), type=need(in,"scopeType",20), scope=need(in,"scopeId",255);
            if(!type.equals("GROUP")&&!type.equals("STATION")&&!type.equals("DEFAULT"))return err(400,"Invalid scope");
            try(Connection c=HmiDb.open()){
                try(PreparedStatement check=c.prepareStatement("SELECT STATUS FROM "+schema()+"HMI_APP_TEMPLATE WHERE ID=? AND PAGE_ID=?")){
                    check.setString(1,templateId);check.setString(2,pageId);
                    try(ResultSet rs=check.executeQuery()){if(!rs.next()||!"PUBLISHED".equals(rs.getString(1)))return err(400,"Only published templates can be assigned");}
                }
                try(PreparedStatement p=c.prepareStatement("INSERT INTO "+schema()+"HMI_APP_ASSIGNMENT(ID,PAGE_ID,SCOPE_TYPE,SCOPE_ID,TEMPLATE_ID,PRIORITY) VALUES(?,?,?,?,?,?)")){
                    p.setString(1,id());p.setString(2,pageId);p.setString(3,type);p.setString(4,scope);p.setString(5,templateId);p.setInt(6,bounded(in,"priority",0,1000,0));p.executeUpdate();
                }
                audit(c,"template.assigned",templateId,type+":"+scope);return json(new JSONObject().put("ok",true));
            }
        }catch(JSONException e){return err(400,e.getMessage());}catch(SQLException e){return dbError(e);}
    }
    private Response storePreferences(String type,String identity,JSONObject input){
        JSONObject prefs=validatePreferences(input);
        try(Connection c=HmiDb.open()){
            int count;
            try(PreparedStatement p=c.prepareStatement("UPDATE "+schema()+"HMI_APP_PREF SET PREFS_JSON=?,UPDATED_AT=? WHERE SCOPE_TYPE=? AND SCOPE_ID=?")){
                clob(p,1,prefs.toString());p.setTimestamp(2,Timestamp.from(Instant.now()));p.setString(3,type);p.setString(4,identity);count=p.executeUpdate();
            }
            if(count==0){try(PreparedStatement p=c.prepareStatement("INSERT INTO "+schema()+"HMI_APP_PREF(SCOPE_TYPE,SCOPE_ID,PREFS_JSON,UPDATED_AT) VALUES (?,?,?,?)")){
                p.setString(1,type);p.setString(2,identity);clob(p,3,prefs.toString());p.setTimestamp(4,Timestamp.from(Instant.now()));p.executeUpdate();
            }}
            audit(c,"preferences.saved",type+":"+identity,"");return json(prefs);
        }catch(SQLException e){return dbError(e);}
    }
    private JSONObject preference(Connection c,String type,String identity)throws SQLException{
        try(PreparedStatement p=c.prepareStatement("SELECT PREFS_JSON FROM "+schema()+"HMI_APP_PREF WHERE SCOPE_TYPE=? AND SCOPE_ID=?")){
            p.setString(1,type);p.setString(2,identity);
            try(ResultSet rs=p.executeQuery()){return rs.next()?objectOrEmpty(clob(rs,"PREFS_JSON")):new JSONObject();}
        }
    }
    private static void merge(JSONObject target,JSONObject changes){for(String k:changes.keySet())target.put(k,changes.get(k));}
    private List<String> groups(Connection c,String userId)throws SQLException{
        List<String> a=new ArrayList<>();
        try(PreparedStatement p=c.prepareStatement("SELECT GROUP_ID FROM "+schema()+"HMI_APP_GROUP_MEMBER WHERE USER_ID=? ORDER BY GROUP_ID")){
            p.setString(1,userId);try(ResultSet rs=p.executeQuery()){while(rs.next())a.add(rs.getString(1));}
        }
        String pers=HmiAuth.persId(c,userId);
        if(pers!=null)try(PreparedStatement p=c.prepareStatement(
                "SELECT GROUP_KEY FROM "+schema()+"HMI_APP_PERSON_GROUP WHERE PERS_ID=? ORDER BY GROUP_KEY")) {
            p.setString(1,pers);
            try(ResultSet rs=p.executeQuery()) { while(rs.next())if(!a.contains(rs.getString(1)))a.add(rs.getString(1)); }
        }
        return a;
    }
    private JSONObject fetchPage(Connection c,String pageId)throws SQLException{
        try(PreparedStatement p=c.prepareStatement("SELECT ID,PAGE_KEY,TITLE,MENU_GROUP,SORT_ORDER,ENABLED,PARENT_PAGE_ID FROM "+schema()+"HMI_APP_PAGE WHERE ID=?")){
            p.setString(1,pageId);try(ResultSet rs=p.executeQuery()){
                return rs.next()?new JSONObject().put("id",rs.getString(1)).put("key",rs.getString(2)).put("title",rs.getString(3))
                    .put("menuGroup",rs.getString(4)).put("order",rs.getInt(5)).put("enabled",rs.getInt(6)!=0)
                    .put("parentPageId",rs.getString(7)==null?JSONObject.NULL:rs.getString(7)):null;
            }
        }
    }
    private boolean pageExists(Connection c,String pageId)throws SQLException{return fetchPage(c,pageId)!=null;}
    private JSONObject resolveTemplate(Connection c,String pageId,String station,List<String> groups)throws SQLException{
        List<String> ids=new ArrayList<>();
        if(station!=null&&!station.isEmpty())ids.add("STATION:"+station);
        for(String g:groups)ids.add("GROUP:"+g);
        ids.add("DEFAULT:*");
        // Distinct selected precedence STATION > GROUP > DEFAULT; highest priority within a scope.
        for(String selection:ids){
            String[] parts=selection.split(":",2);
            try(PreparedStatement p=c.prepareStatement("SELECT T.ID,T.VERSION_NO,T.LAYOUT_JSON FROM "+schema()+"HMI_APP_ASSIGNMENT A JOIN "+schema()+"HMI_APP_TEMPLATE T ON A.TEMPLATE_ID=T.ID WHERE A.PAGE_ID=? AND A.SCOPE_TYPE=? AND A.SCOPE_ID=? AND T.STATUS='PUBLISHED' ORDER BY A.PRIORITY DESC,T.VERSION_NO DESC")){
                p.setString(1,pageId);p.setString(2,parts[0]);p.setString(3,parts[1]);
                try(ResultSet rs=p.executeQuery()){if(rs.next())return new JSONObject().put("id",rs.getString(1)).put("version",rs.getInt(2)).put("layout",objectOrEmpty(clob(rs,"LAYOUT_JSON")));}
            }
        }
        try(PreparedStatement p=c.prepareStatement("SELECT ID,VERSION_NO,LAYOUT_JSON FROM "+schema()+"HMI_APP_TEMPLATE WHERE PAGE_ID=? AND STATUS='PUBLISHED' ORDER BY VERSION_NO DESC")){
            p.setString(1,pageId);try(ResultSet rs=p.executeQuery()){
                return rs.next()?new JSONObject().put("id",rs.getString(1)).put("version",rs.getInt(2)).put("layout",objectOrEmpty(clob(rs,"LAYOUT_JSON"))):null;
            }
        }
    }
    private void audit(Connection c,String action,String entity,String details)throws SQLException{
        try(PreparedStatement p=c.prepareStatement("INSERT INTO "+schema()+"HMI_APP_AUDIT(ID,ACTOR,ACTION_NAME,ENTITY_ID,DETAILS,CREATED_AT) VALUES(?,?,?,?,?,?)")){
            p.setString(1,id());p.setString(2,user());p.setString(3,action);p.setString(4,entity);
            p.setString(5,details.length()>1000?details.substring(0,1000):details);p.setTimestamp(6,Timestamp.from(Instant.now()));p.executeUpdate();
        }
    }
    private Response dbError(Exception ex){
        java.util.logging.Logger.getLogger(HmiApiResource.class.getName()).log(java.util.logging.Level.SEVERE,"HMI DB operation failed",ex);
        return err(500,"Database operation failed; check server logs");
    }
}