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. All SQL is parameterized; auth comes only from GlassFish principal. */
@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", "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 security == null || security.getUserPrincipal() == null ? null : security.getUserPrincipal().getName();
    }
    private boolean role(String name) { return security != null && security.isUserInRole(name); }
    private boolean designer() { return role("hmi-admin") || role("hmi-designer") || role("hmi-publisher"); }
    private boolean publisher() { return role("hmi-admin") || role("hmi-publisher"); }
    private boolean admin() { return role("hmi-admin"); }
    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, "GlassFish authentication required");
        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() {
        HttpSession session = request.getSession(false);
        if (session == null) return false;
        Object token = session.getAttribute(CSRF);
        String provided = request.getHeader("X-CSRF-Token");
        if (!(token instanceof String) || provided == null) return false;
        return java.security.MessageDigest.isEqual(((String) token).getBytes(java.nio.charset.StandardCharsets.UTF_8),
                provided.getBytes(java.nio.charset.StandardCharsets.UTF_8));
    }
    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")) 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");
            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("props",w.optJSONObject("props") == null ? new JSONObject() : w.getJSONObject("props"));
            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;
    }
    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;
    }
    @GET @Path("security/csrf")
    public Response csrf() {
        Response r = denied(true); if (r != null) return r;
        HttpSession s = request.getSession(true);
        String token = (String) s.getAttribute(CSRF);
        if (token == null) {
            byte[] b = new byte[32]; new java.security.SecureRandom().nextBytes(b);
            token = java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(b);
            s.setAttribute(CSRF, token);
        }
        return json(new JSONObject().put("csrf", token).put("user", user())
            .put("designer",designer()).put("publisher",publisher()).put("admin",admin()));
    }
    @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("pages")
    public Response pages() {
        Response r = denied(true); if (r!=null) return r;
        JSONArray a = new JSONArray();
        try (Connection c=HmiDb.open(); PreparedStatement p=c.prepareStatement(
            "SELECT ID,PAGE_KEY,TITLE,MENU_GROUP,SORT_ORDER,ENABLED FROM " + schema() + "HMI_APP_PAGE ORDER BY SORT_ORDER,TITLE"); ResultSet rs=p.executeQuery()) {
            while (rs.next()) {
                if (rs.getInt("ENABLED") == 0 && !designer()) continue;
                a.put(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));
            }
            return json(a);
        } catch (SQLException e) { return dbError(e); }
    }
    @POST @Path("pages") @Consumes(MediaType.APPLICATION_JSON)
    public Response createPage(String body) {
        Response r=writeAllowed(designer()); if(r!=null)return r;
        try {
            JSONObject in=parse(body);
            String key=need(in,"key",120); if(!legalKey(key)) return err(400,"Invalid page key");
            String title=need(in,"title",255), pageId=id();
            String menu=in.optString("menuGroup","HMI"); if(menu.length()>120)return err(400,"Menu too long");
            int order=bounded(in,"order",0,100000,0);
            try (Connection c=HmiDb.open(); PreparedStatement p=c.prepareStatement(
                 "INSERT INTO "+schema()+"HMI_APP_PAGE(ID,PAGE_KEY,TITLE,MENU_GROUP,SORT_ORDER,ENABLED) VALUES (?,?,?,?,?,1)")) {
                p.setString(1,pageId);p.setString(2,key);p.setString(3,title);p.setString(4,menu);p.setInt(5,order);p.executeUpdate();
                audit(c,"page.created",pageId,key);
            }
            return json(new JSONObject().put("id",pageId).put("key",key));
        } catch (JSONException e) { return err(400,e.getMessage()); } catch (SQLException e) { return dbError(e); }
    }
    @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 in=parse(body);String title=need(in,"title",255), menu=in.optString("menuGroup","HMI");
            if(menu.length()>120)return err(400,"Menu too long");
            try (Connection c=HmiDb.open();PreparedStatement p=c.prepareStatement("UPDATE "+schema()+"HMI_APP_PAGE SET TITLE=?,MENU_GROUP=?,SORT_ORDER=?,ENABLED=? WHERE ID=?")) {
                p.setString(1,title);p.setString(2,menu);p.setInt(3,bounded(in,"order",0,100000,0));
                p.setInt(4,in.optBoolean("enabled",true)?1:0);p.setString(5,pageId);
                if(p.executeUpdate()==0)return err(404,"Page not found"); audit(c,"page.updated",pageId,title);
            }
            return json(new JSONObject().put("ok",true));
        } 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));
            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();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)return err(409,"Template not a draft or not found");audit(c,"template.saved",templateId,"");
            }
            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||(!page.getBoolean("enabled")&&!designer()))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();
            for(Object val:layout.getJSONArray("widgets")) {
                JSONObject widget=new JSONObject(val.toString());String widgetId=widget.getString("id");
                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));}
        }
        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 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):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");
    }
}