-- =====================================================================================
-- Script: 01_MARS_956_export_c2d_mpec_data.sql
-- Purpose: Export C2D MPEC historical data to ODS bucket
-- Author: Grzegorz Michalski
-- Created: 2026-02-12
-- MARS Issue: MARS-956
-- Target: mrds_data_dev/ODS/C2D/
-- =====================================================================================

SET SERVEROUTPUT ON SIZE UNLIMITED;
SET TIMING ON;

PROMPT =====================================================================================
PROMPT MARS-956: C2D MPEC Historical Data Export
PROMPT =====================================================================================
PROMPT Export Strategy:
PROMPT - Source: OU_LEGACY_C2D schema tables (operational database)
PROMPT - Target: ODS bucket as CSV files
PROMPT - Method: DATA_EXPORTER.EXPORT_TABLE_DATA
PROMPT - Registration: Files registered in A_SOURCE_FILE_RECEIVED
PROMPT - Path Structure: ODS/C2D/C2D_MPEC_*/
PROMPT =====================================================================================

-- Log export start
INSERT INTO CT_MRDS.A_PROCESS_LOG (PROCESS_NAME, PROCEDURE_NAME, LOG_LEVEL, LOG_MESSAGE, PROCEDURE_PARAMETERS)
VALUES ('MARS-956', 'EXPORT_C2D_MPEC_DATA', 'INFO', 'Starting historical C2D MPEC data export', 
        'Tables: MPEC_ADMIN, MPEC_CONTENT, MPEC_CONTENT_CRITERION');

PROMPT 
PROMPT =====================================================================================
PROMPT PRE-EXPORT CHECK: Verify Existing Files in ODS Bucket
PROMPT =====================================================================================

-- Check 1: MPEC_ADMIN files
DECLARE
    vFileCount NUMBER := 0;
    vRecordCount NUMBER := 0;
    vLocationUri VARCHAR2(1000);
BEGIN
    -- Get bucket URI for DATA bucket
    vLocationUri := CT_MRDS.FILE_MANAGER.GET_BUCKET_URI('DATA') || 'ODS/C2D/C2D_MPEC_ADMIN/';
    
    -- Count existing files
    SELECT COUNT(*)
    INTO vFileCount
    FROM TABLE(DBMS_CLOUD.LIST_OBJECTS(
        credential_name => 'OCI$RESOURCE_PRINCIPAL',
        location_uri => vLocationUri
    ))
    WHERE object_name NOT LIKE '%/';  -- Exclude directories
    
    IF vFileCount > 0 THEN
        DBMS_OUTPUT.PUT_LINE('===============================================================================');
        DBMS_OUTPUT.PUT_LINE('PRE-EXPORT CHECK: MPEC_ADMIN files already exist in DATA bucket');
        DBMS_OUTPUT.PUT_LINE('===============================================================================');
        DBMS_OUTPUT.PUT_LINE('Location: ' || vLocationUri);
        DBMS_OUTPUT.PUT_LINE('Files found: ' || vFileCount);
        DBMS_OUTPUT.PUT_LINE('');
        
        -- List existing files
        DBMS_OUTPUT.PUT_LINE('Existing files:');
        FOR rec IN (
            SELECT object_name, bytes, TO_CHAR(last_modified, 'YYYY-MM-DD HH24:MI:SS') AS modified
            FROM TABLE(DBMS_CLOUD.LIST_OBJECTS(
                credential_name => 'OCI$RESOURCE_PRINCIPAL',
                location_uri => vLocationUri
            ))
            WHERE object_name NOT LIKE '%/'
            ORDER BY object_name
        ) LOOP
            DBMS_OUTPUT.PUT_LINE('  - ' || rec.object_name || ' (' || rec.bytes || ' bytes, ' || rec.modified || ')');
        END LOOP;
        
        -- Count records in external table
        BEGIN
            EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ODS.C2D_MPEC_ADMIN_ODS' INTO vRecordCount;
            DBMS_OUTPUT.PUT_LINE('');
            DBMS_OUTPUT.PUT_LINE('-------------------------------------------------------------------------------');
            DBMS_OUTPUT.PUT_LINE('>>>');
            DBMS_OUTPUT.PUT_LINE('>>> Records currently readable via external table: ' || vRecordCount);
            DBMS_OUTPUT.PUT_LINE('>>>');
            DBMS_OUTPUT.PUT_LINE('-------------------------------------------------------------------------------');
        EXCEPTION
            WHEN OTHERS THEN
                DBMS_OUTPUT.PUT_LINE('');
                DBMS_OUTPUT.PUT_LINE('WARNING: Cannot count records in external table');
                DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
        END;
        
        DBMS_OUTPUT.PUT_LINE('===============================================================================');
        DBMS_OUTPUT.PUT_LINE('');
    ELSE
        DBMS_OUTPUT.PUT_LINE('PRE-EXPORT CHECK: No existing MPEC_ADMIN files found - bucket is clean');
        DBMS_OUTPUT.PUT_LINE('');
    END IF;
END;
/

-- Check 2: MPEC_CONTENT files
DECLARE
    vFileCount NUMBER := 0;
    vRecordCount NUMBER := 0;
    vLocationUri VARCHAR2(1000);
BEGIN
    vLocationUri := CT_MRDS.FILE_MANAGER.GET_BUCKET_URI('DATA') || 'ODS/C2D/C2D_MPEC_CONTENT/';
    
    SELECT COUNT(*)
    INTO vFileCount
    FROM TABLE(DBMS_CLOUD.LIST_OBJECTS(
        credential_name => 'OCI$RESOURCE_PRINCIPAL',
        location_uri => vLocationUri
    ))
    WHERE object_name NOT LIKE '%/';
    
    IF vFileCount > 0 THEN
        DBMS_OUTPUT.PUT_LINE('===============================================================================');
        DBMS_OUTPUT.PUT_LINE('PRE-EXPORT CHECK: MPEC_CONTENT files already exist in DATA bucket');
        DBMS_OUTPUT.PUT_LINE('===============================================================================');
        DBMS_OUTPUT.PUT_LINE('Location: ' || vLocationUri);
        DBMS_OUTPUT.PUT_LINE('Files found: ' || vFileCount);
        DBMS_OUTPUT.PUT_LINE('');
        
        DBMS_OUTPUT.PUT_LINE('Existing files:');
        FOR rec IN (
            SELECT object_name, bytes, TO_CHAR(last_modified, 'YYYY-MM-DD HH24:MI:SS') AS modified
            FROM TABLE(DBMS_CLOUD.LIST_OBJECTS(
                credential_name => 'OCI$RESOURCE_PRINCIPAL',
                location_uri => vLocationUri
            ))
            WHERE object_name NOT LIKE '%/'
            ORDER BY object_name
        ) LOOP
            DBMS_OUTPUT.PUT_LINE('  - ' || rec.object_name || ' (' || rec.bytes || ' bytes, ' || rec.modified || ')');
        END LOOP;
        
        BEGIN
            EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ODS.C2D_MPEC_CONTENT_ODS' INTO vRecordCount;
            DBMS_OUTPUT.PUT_LINE('');
            DBMS_OUTPUT.PUT_LINE('-------------------------------------------------------------------------------');
            DBMS_OUTPUT.PUT_LINE('>>>');
            DBMS_OUTPUT.PUT_LINE('>>> Records currently readable via external table: ' || vRecordCount);
            DBMS_OUTPUT.PUT_LINE('>>>');
            DBMS_OUTPUT.PUT_LINE('-------------------------------------------------------------------------------');
        EXCEPTION
            WHEN OTHERS THEN
                DBMS_OUTPUT.PUT_LINE('');
                DBMS_OUTPUT.PUT_LINE('WARNING: Cannot count records in external table');
                DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
        END;
        
        DBMS_OUTPUT.PUT_LINE('===============================================================================');
        DBMS_OUTPUT.PUT_LINE('');
    ELSE
        DBMS_OUTPUT.PUT_LINE('PRE-EXPORT CHECK: No existing MPEC_CONTENT files found - bucket is clean');
        DBMS_OUTPUT.PUT_LINE('');
    END IF;
END;
/

-- Check 3: MPEC_CONTENT_CRITERION files
DECLARE
    vFileCount NUMBER := 0;
    vRecordCount NUMBER := 0;
    vLocationUri VARCHAR2(1000);
BEGIN
    vLocationUri := CT_MRDS.FILE_MANAGER.GET_BUCKET_URI('DATA') || 'ODS/C2D/C2D_MPEC_CONTENT_CRITERION/';
    
    SELECT COUNT(*)
    INTO vFileCount
    FROM TABLE(DBMS_CLOUD.LIST_OBJECTS(
        credential_name => 'OCI$RESOURCE_PRINCIPAL',
        location_uri => vLocationUri
    ))
    WHERE object_name NOT LIKE '%/';
    
    IF vFileCount > 0 THEN
        DBMS_OUTPUT.PUT_LINE('===============================================================================');
        DBMS_OUTPUT.PUT_LINE('PRE-EXPORT CHECK: MPEC_CONTENT_CRITERION files already exist in DATA bucket');
        DBMS_OUTPUT.PUT_LINE('===============================================================================');
        DBMS_OUTPUT.PUT_LINE('Location: ' || vLocationUri);
        DBMS_OUTPUT.PUT_LINE('Files found: ' || vFileCount);
        DBMS_OUTPUT.PUT_LINE('');
        
        DBMS_OUTPUT.PUT_LINE('Existing files:');
        FOR rec IN (
            SELECT object_name, bytes, TO_CHAR(last_modified, 'YYYY-MM-DD HH24:MI:SS') AS modified
            FROM TABLE(DBMS_CLOUD.LIST_OBJECTS(
                credential_name => 'OCI$RESOURCE_PRINCIPAL',
                location_uri => vLocationUri
            ))
            WHERE object_name NOT LIKE '%/'
            ORDER BY object_name
        ) LOOP
            DBMS_OUTPUT.PUT_LINE('  - ' || rec.object_name || ' (' || rec.bytes || ' bytes, ' || rec.modified || ')');
        END LOOP;
        
        BEGIN
            EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ODS.C2D_MPEC_CONTENT_CRITERION_ODS' INTO vRecordCount;
            DBMS_OUTPUT.PUT_LINE('');
            DBMS_OUTPUT.PUT_LINE('-------------------------------------------------------------------------------');
            DBMS_OUTPUT.PUT_LINE('>>>');
            DBMS_OUTPUT.PUT_LINE('>>> Records currently readable via external table: ' || vRecordCount);
            DBMS_OUTPUT.PUT_LINE('>>>');
            DBMS_OUTPUT.PUT_LINE('-------------------------------------------------------------------------------');
        EXCEPTION
            WHEN OTHERS THEN
                DBMS_OUTPUT.PUT_LINE('');
                DBMS_OUTPUT.PUT_LINE('WARNING: Cannot count records in external table');
                DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
        END;
        
        DBMS_OUTPUT.PUT_LINE('===============================================================================');
        DBMS_OUTPUT.PUT_LINE('');
    ELSE
        DBMS_OUTPUT.PUT_LINE('PRE-EXPORT CHECK: No existing MPEC_CONTENT_CRITERION files found - bucket is clean');
        DBMS_OUTPUT.PUT_LINE('');
    END IF;
END;
/

PROMPT 
PROMPT =====================================================================================
PROMPT PRE-EXPORT: Verify Source and Target Table Readiness
PROMPT =====================================================================================

-- Check source table counts before export
DECLARE
    vAdminRows NUMBER := 0;
    vContentRows NUMBER := 0;
    vCriterionRows NUMBER := 0;
    vTotalSource NUMBER := 0;
    vAdminTarget NUMBER := 0;
    vContentTarget NUMBER := 0;
    vCriterionTarget NUMBER := 0;
    vTotalTarget NUMBER := 0;
BEGIN
    -- Source table counts
    EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM OU_LEGACY_C2D.MPEC_ADMIN' INTO vAdminRows;
    EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM OU_LEGACY_C2D.MPEC_CONTENT' INTO vContentRows;
    EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM OU_LEGACY_C2D.MPEC_CONTENT_CRITERION' INTO vCriterionRows;
    vTotalSource := vAdminRows + vContentRows + vCriterionRows;
    
    DBMS_OUTPUT.PUT_LINE('Source table record counts (pre-export):');
    DBMS_OUTPUT.PUT_LINE('- MPEC_ADMIN: ' || vAdminRows || ' records');
    DBMS_OUTPUT.PUT_LINE('- MPEC_CONTENT: ' || vContentRows || ' records');
    DBMS_OUTPUT.PUT_LINE('- MPEC_CONTENT_CRITERION: ' || vCriterionRows || ' records');
    DBMS_OUTPUT.PUT_LINE('- TOTAL SOURCE: ' || vTotalSource || ' records');
    
    -- Target external table counts (current state)
    BEGIN
        EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ODS.C2D_MPEC_ADMIN_ODS' INTO vAdminTarget;
    EXCEPTION
        WHEN OTHERS THEN 
            IF SQLCODE IN (-29913, -29400) OR SQLERRM LIKE '%KUP-13023%' THEN
                vAdminTarget := 0;  -- Empty is expected
            ELSE
                vAdminTarget := -1;  -- Error
            END IF;
    END;
    
    BEGIN
        EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ODS.C2D_MPEC_CONTENT_ODS' INTO vContentTarget;
    EXCEPTION
        WHEN OTHERS THEN 
            IF SQLCODE IN (-29913, -29400) OR SQLERRM LIKE '%KUP-13023%' THEN
                vContentTarget := 0;
            ELSE
                vContentTarget := -1;
            END IF;
    END;
    
    BEGIN
        EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ODS.C2D_MPEC_CONTENT_CRITERION_ODS' INTO vCriterionTarget;
    EXCEPTION
        WHEN OTHERS THEN 
            IF SQLCODE IN (-29913, -29400) OR SQLERRM LIKE '%KUP-13023%' THEN
                vCriterionTarget := 0;
            ELSE
                vCriterionTarget := -1;
            END IF;
    END;
    
    IF vAdminTarget >= 0 AND vContentTarget >= 0 AND vCriterionTarget >= 0 THEN
        vTotalTarget := vAdminTarget + vContentTarget + vCriterionTarget;
    ELSE
        vTotalTarget := -1;  -- Error state
    END IF;
    
    DBMS_OUTPUT.PUT_LINE('');
    DBMS_OUTPUT.PUT_LINE('Target external table record counts (pre-export):');
    DBMS_OUTPUT.PUT_LINE('- C2D_MPEC_ADMIN_ODS: ' || 
        CASE WHEN vAdminTarget = -1 THEN 'ERROR/INACCESSIBLE' ELSE TO_CHAR(vAdminTarget) END);
    DBMS_OUTPUT.PUT_LINE('- C2D_MPEC_CONTENT_ODS: ' || 
        CASE WHEN vContentTarget = -1 THEN 'ERROR/INACCESSIBLE' ELSE TO_CHAR(vContentTarget) END);
    DBMS_OUTPUT.PUT_LINE('- C2D_MPEC_CONTENT_CRITERION_ODS: ' || 
        CASE WHEN vCriterionTarget = -1 THEN 'ERROR/INACCESSIBLE' ELSE TO_CHAR(vCriterionTarget) END);
    DBMS_OUTPUT.PUT_LINE('- TOTAL TARGET: ' || 
        CASE WHEN vTotalTarget = -1 THEN 'ERROR/INACCESSIBLE' ELSE TO_CHAR(vTotalTarget) END);
        
    IF vTotalSource > 0 THEN
        DBMS_OUTPUT.PUT_LINE('SUCCESS: Source tables contain data - ready for export');
    ELSE
        DBMS_OUTPUT.PUT_LINE('ERROR: WARNING: No source data found');
    END IF;
    
    IF vTotalTarget = 0 THEN
        DBMS_OUTPUT.PUT_LINE('SUCCESS: Target external tables are clean - ready for fresh export');
    ELSIF vTotalTarget > 0 THEN
        DBMS_OUTPUT.PUT_LINE('WARNING: Target tables contain ' || vTotalTarget || ' records - may be re-run');
    ELSE
        DBMS_OUTPUT.PUT_LINE('ERROR: Cannot access target external tables');
    END IF;
    
    DBMS_OUTPUT.PUT_LINE('');
    DBMS_OUTPUT.PUT_LINE('Proceeding with export...');
END;
/

PROMPT 
PROMPT =====================================================================================
PROMPT TABLE 1/3: OU_LEGACY_C2D.MPEC_ADMIN -> ODS/C2D/C2D_MPEC_ADMIN
PROMPT =====================================================================================

BEGIN
    CT_MRDS.DATA_EXPORTER.EXPORT_TABLE_DATA(
        pSchemaName        => 'OU_LEGACY_C2D',
        pTableName         => 'MPEC_ADMIN', 
        pKeyColumnName     => 'A_ETL_LOAD_SET_FK',  -- ETL key for data lookup
        pBucketArea        => 'ODS',
        pFolderName        => 'ODS/C2D/C2D_MPEC_ADMIN',
        pTemplateTableName => 'CT_ET_TEMPLATES.C2D_MPEC_ADMIN', -- Template for column order
        pMaxFileSize       => 104857600,                 -- 100MB max file size
        pRegisterExport    => TRUE,                      -- Register files in A_SOURCE_FILE_RECEIVED
        pProcessName       => 'MARS-956'                 -- Process identifier for tracking
    );
    
    DBMS_OUTPUT.PUT_LINE('SUCCESS: MPEC_ADMIN export completed successfully');
EXCEPTION
    WHEN OTHERS THEN
        DECLARE
            vErrorMsg VARCHAR2(4000) := SUBSTR(SQLERRM, 1, 4000);
        BEGIN
            DBMS_OUTPUT.PUT_LINE('ERROR: MPEC_ADMIN export failed: ' || vErrorMsg);
            -- Log error using proper ENV_MANAGER pattern
            INSERT INTO CT_MRDS.A_PROCESS_LOG 
                (guid, Username, Osuser, Machine, Module, process_name, procedure_name, procedure_parameters, log_level, log_message)
            VALUES 
                ('MARS-956', USER, SYS_CONTEXT('USERENV','OS_USER'), SYS_CONTEXT('USERENV','HOST'), 
                 'MARS-956', 'MARS-956', 'EXPORT_MPEC_ADMIN', NULL, 'ERROR', 
                 'Export failed: ' || vErrorMsg);
            COMMIT;
        END;
END;
/

PROMPT 
PROMPT =====================================================================================
PROMPT TABLE 2/3: OU_LEGACY_C2D.MPEC_CONTENT -> ODS/C2D/C2D_MPEC_CONTENT
PROMPT =====================================================================================

BEGIN
    CT_MRDS.DATA_EXPORTER.EXPORT_TABLE_DATA(
        pSchemaName        => 'OU_LEGACY_C2D',
        pTableName         => 'MPEC_CONTENT',
        pKeyColumnName     => 'A_ETL_LOAD_SET_FK', 
        pBucketArea        => 'ODS',
        pFolderName        => 'ODS/C2D/C2D_MPEC_CONTENT',
        pTemplateTableName => 'CT_ET_TEMPLATES.C2D_MPEC_CONTENT',
        pMaxFileSize       => 104857600,  -- 100MB max file size
        pRegisterExport    => TRUE,
        pProcessName       => 'MARS-956'  -- Process identifier for tracking
    );
    
    DBMS_OUTPUT.PUT_LINE('SUCCESS: MPEC_CONTENT export completed successfully');
EXCEPTION
    WHEN OTHERS THEN
        DECLARE
            vErrorMsg VARCHAR2(4000) := SUBSTR(SQLERRM, 1, 4000);
        BEGIN
            DBMS_OUTPUT.PUT_LINE('ERROR: MPEC_CONTENT export failed: ' || vErrorMsg);
            -- Log error using proper ENV_MANAGER pattern
            INSERT INTO CT_MRDS.A_PROCESS_LOG 
                (guid, Username, Osuser, Machine, Module, process_name, procedure_name, procedure_parameters, log_level, log_message)
            VALUES 
                ('MARS-956', USER, SYS_CONTEXT('USERENV','OS_USER'), SYS_CONTEXT('USERENV','HOST'), 
                 'MARS-956', 'MARS-956', 'EXPORT_MPEC_CONTENT', NULL, 'ERROR', 
                 'Export failed: ' || vErrorMsg);
            COMMIT;
        END;
END;
/

PROMPT 
PROMPT =====================================================================================
PROMPT TABLE 3/3: OU_LEGACY_C2D.MPEC_CONTENT_CRITERION -> ODS/C2D/C2D_MPEC_CONTENT_CRITERION
PROMPT =====================================================================================

BEGIN
    CT_MRDS.DATA_EXPORTER.EXPORT_TABLE_DATA(
        pSchemaName        => 'OU_LEGACY_C2D',
        pTableName         => 'MPEC_CONTENT_CRITERION',
        pKeyColumnName     => 'A_ETL_LOAD_SET_FK',
        pBucketArea        => 'ODS',
        pFolderName        => 'ODS/C2D/C2D_MPEC_CONTENT_CRITERION',
        pTemplateTableName => 'CT_ET_TEMPLATES.C2D_MPEC_CONTENT_CRITERION',
        pMaxFileSize       => 104857600,  -- 100MB max file size
        pRegisterExport    => TRUE,
        pProcessName       => 'MARS-956'  -- Process identifier for tracking
    );
    
    DBMS_OUTPUT.PUT_LINE('SUCCESS: MPEC_CONTENT_CRITERION export completed successfully');
EXCEPTION
    WHEN OTHERS THEN
        DECLARE
            vErrorMsg VARCHAR2(4000) := SUBSTR(SQLERRM, 1, 4000);
        BEGIN
            DBMS_OUTPUT.PUT_LINE('ERROR: MPEC_CONTENT_CRITERION export failed: ' || vErrorMsg);
            -- Log error using proper ENV_MANAGER pattern
            INSERT INTO CT_MRDS.A_PROCESS_LOG 
                (guid, Username, Osuser, Machine, Module, process_name, procedure_name, procedure_parameters, log_level, log_message)
            VALUES 
                ('MARS-956', USER, SYS_CONTEXT('USERENV','OS_USER'), SYS_CONTEXT('USERENV','HOST'), 
                 'MARS-956', 'MARS-956', 'EXPORT_MPEC_CONTENT_CRITERION', NULL, 'ERROR', 
                 'Export failed: ' || vErrorMsg);
            COMMIT;
        END;
END;
/

PROMPT 
PROMPT =====================================================================================
PROMPT Export Summary - Checking Results
PROMPT =====================================================================================

-- Log completion
INSERT INTO CT_MRDS.A_PROCESS_LOG (PROCESS_NAME, PROCEDURE_NAME, LOG_LEVEL, LOG_MESSAGE)
VALUES ('MARS-956', 'EXPORT_C2D_MPEC_DATA', 'INFO', 'All C2D MPEC historical exports completed successfully');

PROMPT 
PROMPT =====================================================================================
PROMPT MARS-956 C2D MPEC Export Completed Successfully!
PROMPT =====================================================================================
PROMPT POST-EXPORT: Source vs Target Record Count Comparison
PROMPT =====================================================================================

-- Verify record counts after export
DECLARE
    vAdminSource NUMBER := 0;
    vContentSource NUMBER := 0;
    vCriterionSource NUMBER := 0;
    vTotalSource NUMBER := 0;
    vAdminTarget NUMBER := 0;
    vContentTarget NUMBER := 0;
    vCriterionTarget NUMBER := 0;
    vTotalTarget NUMBER := 0;
    vMismatchCount NUMBER := 0;
BEGIN
    -- Source table counts
    EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM OU_LEGACY_C2D.MPEC_ADMIN' INTO vAdminSource;
    EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM OU_LEGACY_C2D.MPEC_CONTENT' INTO vContentSource;
    EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM OU_LEGACY_C2D.MPEC_CONTENT_CRITERION' INTO vCriterionSource;
    vTotalSource := vAdminSource + vContentSource + vCriterionSource;
    
    -- Target external table counts
    BEGIN
        EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ODS.C2D_MPEC_ADMIN_ODS' INTO vAdminTarget;
        EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ODS.C2D_MPEC_CONTENT_ODS' INTO vContentTarget;
        EXECUTE IMMEDIATE 'SELECT COUNT(*) FROM ODS.C2D_MPEC_CONTENT_CRITERION_ODS' INTO vCriterionTarget;
        vTotalTarget := vAdminTarget + vContentTarget + vCriterionTarget;
        
        DBMS_OUTPUT.PUT_LINE('POST-EXPORT VERIFICATION SUMMARY');
        DBMS_OUTPUT.PUT_LINE('=====================================');
        DBMS_OUTPUT.PUT_LINE('Table                          | Source   | Target   | Match');
        DBMS_OUTPUT.PUT_LINE('-----------------------------------------------------------');
        
        -- MPEC_ADMIN comparison
        DBMS_OUTPUT.PUT_LINE('MPEC_ADMIN                     | ' || 
            RPAD(vAdminSource, 8) || ' | ' || 
            RPAD(vAdminTarget, 8) || ' | ' ||
            CASE WHEN vAdminSource = vAdminTarget THEN 'OK' ELSE 'MISMATCH' END);
        IF vAdminSource != vAdminTarget THEN vMismatchCount := vMismatchCount + 1; END IF;
        
        -- MPEC_CONTENT comparison
        DBMS_OUTPUT.PUT_LINE('MPEC_CONTENT                   | ' || 
            RPAD(vContentSource, 8) || ' | ' || 
            RPAD(vContentTarget, 8) || ' | ' ||
            CASE WHEN vContentSource = vContentTarget THEN 'OK' ELSE 'MISMATCH' END);
        IF vContentSource != vContentTarget THEN vMismatchCount := vMismatchCount + 1; END IF;
        
        -- MPEC_CONTENT_CRITERION comparison
        DBMS_OUTPUT.PUT_LINE('MPEC_CONTENT_CRITERION         | ' || 
            RPAD(vCriterionSource, 8) || ' | ' || 
            RPAD(vCriterionTarget, 8) || ' | ' ||
            CASE WHEN vCriterionSource = vCriterionTarget THEN 'OK' ELSE 'MISMATCH' END);
        IF vCriterionSource != vCriterionTarget THEN vMismatchCount := vMismatchCount + 1; END IF;
        
        DBMS_OUTPUT.PUT_LINE('-----------------------------------------------------------');
        DBMS_OUTPUT.PUT_LINE('TOTAL                          | ' || 
            RPAD(vTotalSource, 8) || ' | ' || 
            RPAD(vTotalTarget, 8) || ' | ' ||
            CASE WHEN vTotalSource = vTotalTarget THEN 'OK' ELSE 'MISMATCH' END);
        
        DBMS_OUTPUT.PUT_LINE('');
        IF vMismatchCount = 0 THEN
            DBMS_OUTPUT.PUT_LINE('SUCCESS: All record counts match - export verified');
        ELSE
            DBMS_OUTPUT.PUT_LINE('WARNING: ' || vMismatchCount || ' table(s) have record count mismatches');
            DBMS_OUTPUT.PUT_LINE('  Please review export logs and external table access permissions');
        END IF;
        
    EXCEPTION
        WHEN OTHERS THEN
            DBMS_OUTPUT.PUT_LINE('ERROR: Cannot verify target external tables post-export');
            DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
            DBMS_OUTPUT.PUT_LINE('Please check external table configuration and ODS bucket access');
    END;
END;
/

-- Log export completion
INSERT INTO CT_MRDS.A_PROCESS_LOG (PROCESS_NAME, PROCEDURE_NAME, LOG_LEVEL, LOG_MESSAGE, PROCEDURE_PARAMETERS)
VALUES ('MARS-956', 'EXPORT_C2D_MPEC_DATA', 'INFO', 'Historical C2D MPEC data export completed', 
        'Check verification scripts for detailed results');

COMMIT;

PROMPT 
PROMPT =====================================================================================
PROMPT MARS-956 C2D MPEC Historical Data Export - COMPLETED
PROMPT 
PROMPT Next steps:
PROMPT 1. Run: @02_MARS_956_verify_exports.sql (verify file registration)
PROMPT 2. Run: @03_MARS_956_verify_data_integrity.sql (full data verification)
PROMPT =====================================================================================