-- HMM carrier report template storage and DBMS_CLOUD_AI_AGENT custom tool.
-- Run as ADMIN. Load the approved HTML template into HMM_REPORT_TEMPLATES
-- through the deployment loader before enabling the MCP tool.
WHENEVER SQLERROR EXIT SQL.SQLCODE ROLLBACK
SET DEFINE OFF

CREATE TABLE hmm_report_templates (
  template_key       VARCHAR2(64) PRIMARY KEY,
  template_version   VARCHAR2(32) NOT NULL,
  html_template      CLOB NOT NULL,
  active_yn          CHAR(1) DEFAULT 'Y' NOT NULL,
  created_at         TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL,
  updated_at         TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL,
  CONSTRAINT hmm_report_templates_active_ck CHECK (active_yn IN ('Y', 'N'))
);

CREATE OR REPLACE PACKAGE hmm_report_render_pkg AUTHID DEFINER AS
  FUNCTION render_carrier_report(p_report_json IN CLOB) RETURN CLOB;
END hmm_report_render_pkg;
/

CREATE OR REPLACE PACKAGE BODY hmm_report_render_pkg AS
  FUNCTION render_carrier_report(p_report_json IN CLOB) RETURN CLOB IS
    l_template CLOB;
    l_data CLOB;
    l_html VARCHAR2(32767);
    l_result CLOB;
  BEGIN
    IF p_report_json IS NULL OR dbms_lob.getlength(p_report_json) > 64000 THEN
      raise_application_error(-20101, 'Invalid report payload size.');
    END IF;
    IF NOT json_exists(p_report_json, '$.report') OR NOT json_exists(p_report_json, '$.rows') THEN
      raise_application_error(-20102, 'Report payload requires report and rows.');
    END IF;
    SELECT html_template INTO l_template
      FROM hmm_report_templates
     WHERE template_key = 'hmm-carrier-performance'
       AND active_yn = 'Y';
    l_data := replace(p_report_json, '</', '<\/');
    l_html := dbms_lob.substr(replace(l_template, '__REPORT_DATA__', l_data), 32767, 1);
    SELECT json_object(
      'status' VALUE 'ok',
      'template' VALUE 'hmm-carrier-performance',
      'html' VALUE l_html
      RETURNING CLOB
    ) INTO l_result FROM dual;
    RETURN l_result;
  EXCEPTION
    WHEN no_data_found THEN
      raise_application_error(-20103, 'Active report template is not installed.');
  END render_carrier_report;
END hmm_report_render_pkg;
/

BEGIN
  DBMS_CLOUD_AI_AGENT.DROP_TOOL('HMM_CARRIER_REPORT_RENDERER', force => TRUE);
  DBMS_CLOUD_AI_AGENT.CREATE_TOOL(
    tool_name => 'HMM_CARRIER_REPORT_RENDERER',
    attributes => q'~{
      "instruction": "Render the supplied carrier-performance payload with the approved HMM HTML template. Do not query data and do not alter the supplied values.",
      "function": "HMM_REPORT_RENDER_PKG.RENDER_CARRIER_REPORT",
      "tool_inputs": [{"name":"P_REPORT_JSON","description":"Normalized carrier performance report JSON."}]
    }~',
    status => 'ENABLED',
    description => 'Renders approved HMM carrier-performance HTML from already-authorized query results.'
  );
END;
/

SELECT tool_name, status
  FROM user_ai_agent_tools
 WHERE tool_name = 'HMM_CARRIER_REPORT_RENDERER';
