-- Build one generalized runtime Few-shot pattern for every customer QA case.
-- The source benchmark remains evaluation-only; this derived record contains
-- no customer game name, date literal, expected result, or physical CZN object.

DECLARE
  v_pattern_question CLOB;
  v_pattern_sql      CLOB;
  v_embedding_input  CLOB;
  v_embedding        VECTOR;
  v_object_role      VARCHAR2(64);
  v_exists           NUMBER;

  FUNCTION generalized_question(p_question CLOB) RETURN CLOB IS
    v_value CLOB := p_question;
  BEGIN
    -- Resolved names/aliases become a semantic game placeholder.
    FOR token IN (
      SELECT column_value AS value
        FROM TABLE(sys.odcivarchar2list(
          '카오스 제로 나이트메어', '카오스제로나이트메어', 'Chaos Zero Nightmare',
          'STOVE_CHAOSZERO', '카제나', 'CZN', 'Bubblyz', '버블리즈',
          '로드나인', '로나', '테스트게임', 'BUBBLYZ', 'LORDNINE'
        ))
    ) LOOP
      v_value := REPLACE(v_value, token.value, '<게임>');
    END LOOP;
    v_value := REGEXP_REPLACE(v_value, '[0-9]{4}년[[:space:]]*[0-9]{1,2}월[[:space:]]*[0-9]{1,2}일', '<기준일>');
    v_value := REGEXP_REPLACE(v_value, '[0-9]{4}-[0-9]{2}-[0-9]{2}', '<기준일>');
    RETURN v_value;
  END;

  FUNCTION generalized_sql(p_sql CLOB) RETURN CLOB IS
    v_value CLOB := p_sql;
  BEGIN
    -- Physical game objects become logical roles. Common dimensions remain
    -- logical as well so the current metadata/plan selects real objects.
    v_value := REPLACE(v_value, '"SGMP_POC"."CZN_COMN_USER_MST"', '<RESOLVED_GAME_USER_MASTER>');
    v_value := REPLACE(v_value, '"SGMP_POC"."CZN_COMN_CHARACTER_MST"', '<RESOLVED_GAME_CHARACTER_MASTER>');
    v_value := REPLACE(v_value, '"SGMP_POC"."CZN_CUSTOM_GOODS_HAVE_TXN"', '<RESOLVED_GAME_GOODS_HOLDINGS>');
    v_value := REPLACE(v_value, '"SGMP_POC"."CZN_CUSTOM_GOODS_CHANGE_TXN"', '<RESOLVED_GAME_GOODS_CHANGE>');
    v_value := REPLACE(v_value, '"SGMP_POC"."CZN_CUSTOM_BIZ_USER_TXN"', '<RESOLVED_GAME_BUSINESS_USER>');
    v_value := REPLACE(v_value, '"SGMP_POC"."CZN_CUSTOM_USER_GOODS_TXN"', '<RESOLVED_GAME_USER_GOODS>');
    v_value := REPLACE(v_value, '"SGMP_POC"."COMN_SALES_TXN"', '<APPROVED_SALES_TRANSACTION>');
    v_value := REPLACE(v_value, '"SGMP_POC"."COMN_REFUND_TXN"', '<APPROVED_REFUND_TRANSACTION>');
    v_value := REPLACE(v_value, '"SGMP_POC"."COMN_GAME_ALIAS_BAS"', '<GAME_ALIAS_CATALOG>');
    v_value := REPLACE(v_value, '"SGMP_POC"."COMN_COUNTRY_BAS"', '<COUNTRY_DIMENSION>');
    v_value := REPLACE(v_value, '"SGMP_POC"."CZN_COMN_SVC_DIM_BAS"', '<RESOLVED_GAME_SERVICE_DIMENSION>');
    v_value := REPLACE(v_value, 'STOVE_CHAOSZERO', '<RESOLVED_GAME_ID>');
    v_value := REPLACE(v_value, '''카제나''', '<RESOLVED_GAME_NAME>');
    v_value := REPLACE(v_value, '''CZN''', '<RESOLVED_GAME_PREFIX>');
    v_value := REGEXP_REPLACE(v_value, 'CZN_[A-Z0-9_]+', '<RESOLVED_GAME_OBJECT>');
    v_value := REPLACE(v_value, '카제나', '<RESOLVED_GAME_NAME>');
    v_value := REPLACE(v_value, '카오스 제로 나이트메어', '<RESOLVED_GAME_NAME>');
    v_value := REPLACE(v_value, '카오스제로나이트메어', '<RESOLVED_GAME_NAME>');
    v_value := REPLACE(v_value, 'CZN', '<RESOLVED_GAME_PREFIX>');
    v_value := REPLACE(v_value, 'BUBBLYZ', '<RESOLVED_GAME_ID>');
    v_value := REPLACE(v_value, 'Bubblyz', '<RESOLVED_GAME_NAME>');
    v_value := REPLACE(v_value, '버블리즈', '<RESOLVED_GAME_NAME>');
    v_value := REPLACE(v_value, 'LORDNINE', '<RESOLVED_GAME_ID>');
    v_value := REPLACE(v_value, '로드나인', '<RESOLVED_GAME_NAME>');
    v_value := REPLACE(v_value, '테스트게임', '<RESOLVED_GAME_NAME>');
    v_value := REGEXP_REPLACE(v_value, 'TO_DATE\(''[0-9]{4}-[0-9]{2}-[0-9]{2}'', ''YYYY-MM-DD''\)', '<BUSINESS_DATE>');
    v_value := REGEXP_REPLACE(v_value, 'TO_DATE\(''[0-9]{8}'', ''YYYYMMDD''\)', '<BUSINESS_DATE>');
    v_value := REGEXP_REPLACE(v_value, 'DATE ''[0-9]{4}-[0-9]{2}-[0-9]{2}''', '<BUSINESS_DATE>');
    RETURN v_value;
  END;

  FUNCTION role_of(p_sql CLOB) RETURN VARCHAR2 IS
  BEGIN
    IF DBMS_LOB.INSTR(p_sql, 'CZN_COMN_CHARACTER_MST') > 0 THEN
      RETURN 'GAME_CHARACTER_MASTER';
    ELSIF DBMS_LOB.INSTR(p_sql, 'CZN_CUSTOM_GOODS_HAVE_TXN') > 0 THEN
      RETURN 'GAME_GOODS_HOLDINGS';
    ELSIF DBMS_LOB.INSTR(p_sql, 'CZN_CUSTOM_GOODS_CHANGE_TXN') > 0 THEN
      RETURN 'GAME_GOODS_CHANGE';
    ELSIF DBMS_LOB.INSTR(p_sql, 'CZN_CUSTOM_BIZ_USER_TXN') > 0 THEN
      RETURN 'GAME_BUSINESS_USER';
    ELSIF DBMS_LOB.INSTR(p_sql, 'COMN_SALES_TXN') > 0 THEN
      RETURN 'SALES_TRANSACTION';
    ELSIF DBMS_LOB.INSTR(p_sql, 'COMN_REFUND_TXN') > 0 THEN
      RETURN 'REFUND_TRANSACTION';
    ELSIF DBMS_LOB.INSTR(p_sql, 'CZN_COMN_USER_MST') > 0 THEN
      RETURN 'GAME_USER_MASTER';
    END IF;
    RETURN 'METADATA_OR_OPERATION';
  END;
BEGIN
  FOR source_row IN (
    SELECT example_id, source_case_id, question, answer_sql
      FROM sg_qa_vector_example
     WHERE source_type = 'CUSTOMER_QA_BENCHMARK'
     ORDER BY source_case_id
  ) LOOP
    v_pattern_question := generalized_question(source_row.question);
    v_pattern_sql := generalized_sql(source_row.answer_sql);
    v_object_role := role_of(source_row.answer_sql);
    v_embedding_input := TO_CLOB('Generalized question pattern: ') || v_pattern_question
      || CHR(10) || 'Logical object role: ' || v_object_role
      || CHR(10) || 'Structural SQL template: ' || v_pattern_sql
      || CHR(10) || 'Use only current game scope metadata and replace placeholders from the current request.';

    -- A generalized runtime pattern must not contain known customer answer
    -- identifiers or fixed business-date literals.
    IF REGEXP_LIKE(v_pattern_question,
          '카제나|버블리즈|Bubblyz|로드나인|테스트게임|[0-9]{4}년|[0-9]{4}-[0-9]{2}-[0-9]{2}', 'i')
       OR REGEXP_LIKE(v_pattern_sql,
          'CZN_|STOVE_CHAOSZERO|카제나|버블리즈|Bubblyz|[0-9]{4}-[0-9]{2}-[0-9]{2}', 'i') THEN
      RAISE_APPLICATION_ERROR(-20061, 'Generalization leak in ' || source_row.source_case_id);
    END IF;

    v_embedding := DBMS_VECTOR.UTL_TO_EMBEDDING(
      v_embedding_input,
      JSON(sg_qa_vector_params('search_document'))
    );

    SELECT COUNT(*)
      INTO v_exists
      FROM sg_qa_vector_example
     WHERE source_type = 'GENERALIZED_QUESTION_PATTERN'
       AND source_case_id = 'PAT-' || source_row.source_case_id;

    IF v_exists = 0 THEN
      INSERT INTO sg_qa_vector_example (
        question, answer_sql, answer_text, embedding_input, embedding, embedding_model,
        reference_status, reference_kind, target_type, object_role,
        inspection_status, inspection_note, verified_at, verified_by,
        source_case_id, source_type
      ) VALUES (
        v_pattern_question,
        v_pattern_sql,
        'Question-specific generalized Few-shot. Structural only: it contains no customer game, date, result, or executable answer. First decide whether this pattern is applicable; then apply the authoritative NONE/SINGLE/MULTI/ALL game plan and replace placeholders from current metadata.',
        v_embedding_input,
        v_embedding,
        'cohere.embed-v4.0',
        'APPROVED', 'SQL_TEMPLATE', 'ANY', v_object_role,
        'VERIFIED',
        'Derived from a customer QA structure after game/date/result/object leakage validation; runtime uses this generalized pattern only.',
        SYSTIMESTAMP, 'SGMP_POC_PATTERN_REVIEW',
        'PAT-' || source_row.source_case_id, 'GENERALIZED_QUESTION_PATTERN'
      );
    ELSE
      UPDATE sg_qa_vector_example
         SET question = v_pattern_question,
             answer_sql = v_pattern_sql,
             answer_text = 'Question-specific generalized Few-shot. Structural only: it contains no customer game, date, result, or executable answer. First decide whether this pattern is applicable; then apply the authoritative NONE/SINGLE/MULTI/ALL game plan and replace placeholders from current metadata.',
             embedding_input = v_embedding_input,
             embedding = v_embedding,
             object_role = v_object_role,
             reference_status = 'APPROVED',
             inspection_status = 'VERIFIED',
             inspection_note = 'Derived from a customer QA structure after game/date/result/object leakage validation; runtime uses this generalized pattern only.',
             verified_at = SYSTIMESTAMP,
             verified_by = 'SGMP_POC_PATTERN_REVIEW'
       WHERE source_type = 'GENERALIZED_QUESTION_PATTERN'
         AND source_case_id = 'PAT-' || source_row.source_case_id;
    END IF;
  END LOOP;
  COMMIT;
END;
/

SELECT source_type, reference_status, COUNT(*) AS example_count
  FROM sg_qa_vector_example
 GROUP BY source_type, reference_status
 ORDER BY source_type, reference_status;
