"use strict";
/**
 * Enhanced Monitoring Generator
 *
 * Generates comprehensive monitoring, logging, and observability configurations
 * from the enhanced schema monitoring section.
 *
 * Supports:
 * - APM: Datadog, New Relic, App Insights
 * - Error Tracking: Sentry, Bugsnag, Rollbar
 * - Logging: Winston, Pino, Bunyan
 * - Distributed Tracing: Jaeger, Zipkin, Datadog
 * - Custom Metrics
 * - Alerting
 */
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.EnhancedMonitoringGenerator = void 0;
const path = __importStar(require("path"));
class EnhancedMonitoringGenerator {
    id = 'enhanced-monitoring';
    name = 'Enhanced Monitoring Generator';
    description = 'Generates comprehensive monitoring and observability configurations from enhanced schema';
    generate(context) {
        const { workflow, outputDirectory } = context;
        const files = [];
        if (!workflow.monitoring) {
            return { files: [] };
        }
        const monitoring = workflow.monitoring;
        // Find backend and frontend components
        const backendComponent = Object.entries(workflow.stack).find(([_, c]) => c.type === 'backend');
        const frontendComponent = Object.entries(workflow.stack).find(([_, c]) => c.type === 'frontend');
        // Generate backend monitoring
        if (backendComponent) {
            const [componentName] = backendComponent;
            files.push(...this.generateBackendMonitoring(componentName, monitoring, outputDirectory));
        }
        // Generate frontend monitoring
        if (frontendComponent && (monitoring.error_tracking?.frontend || monitoring.apm)) {
            const [componentName] = frontendComponent;
            files.push(...this.generateFrontendMonitoring(componentName, monitoring, outputDirectory));
        }
        // Generate shared monitoring configs
        files.push(...this.generateSharedMonitoring(monitoring, outputDirectory));
        return { files };
    }
    /**
     * Generate backend monitoring configuration
     */
    generateBackendMonitoring(componentName, monitoring, outputDir) {
        const files = [];
        const componentDir = path.join(outputDir, componentName);
        // Generate logging configuration
        if (monitoring.logging) {
            files.push(this.generateLoggingConfig(componentDir, monitoring.logging));
            files.push(this.generateLoggerSetup(componentDir, monitoring.logging));
        }
        // Generate error tracking
        if (monitoring.error_tracking?.backend !== false) {
            files.push(this.generateErrorTrackingSetup(componentDir, monitoring.error_tracking));
        }
        // Generate APM
        if (monitoring.apm) {
            files.push(this.generateAPMSetup(componentDir, monitoring.apm));
        }
        // Generate tracing
        if (monitoring.tracing) {
            files.push(this.generateTracingSetup(componentDir, monitoring.tracing));
        }
        // Generate metrics
        if (monitoring.metrics) {
            files.push(this.generateMetricsSetup(componentDir, monitoring.metrics));
        }
        return files;
    }
    /**
     * Generate frontend monitoring configuration
     */
    generateFrontendMonitoring(componentName, monitoring, outputDir) {
        const files = [];
        const componentDir = path.join(outputDir, componentName);
        // Generate error tracking for frontend
        if (monitoring.error_tracking?.frontend) {
            files.push(this.generateFrontendErrorTracking(componentDir, monitoring.error_tracking));
        }
        // Generate frontend APM
        if (monitoring.apm) {
            files.push(this.generateFrontendAPM(componentDir, monitoring.apm));
        }
        return files;
    }
    /**
     * Generate shared monitoring configurations
     */
    generateSharedMonitoring(monitoring, outputDir) {
        const files = [];
        // Generate alert definitions
        if (monitoring.alerts && monitoring.alerts.length > 0) {
            files.push(this.generateAlertConfig(outputDir, monitoring.alerts));
        }
        return files;
    }
    /**
     * Generate logging configuration file
     */
    generateLoggingConfig(componentDir, logging) {
        const provider = logging?.provider || 'winston';
        let content = '';
        if (provider === 'winston') {
            content = this.generateWinstonConfig(logging);
        }
        else if (provider === 'pino') {
            content = this.generatePinoConfig(logging);
        }
        else if (provider === 'bunyan') {
            content = this.generateBunyanConfig(logging);
        }
        else {
            content = this.generateGenericLoggingConfig(logging);
        }
        return {
            path: path.join(componentDir, 'src/config/logging.ts'),
            content,
            overwrite: false,
        };
    }
    generateWinstonConfig(logging) {
        const level = logging?.level || 'info';
        const transports = logging?.transports || [{ type: 'console' }];
        const transportCode = transports.map(transport => {
            if (transport.type === 'console') {
                return `new winston.transports.Console({
      format: winston.format.combine(
        winston.format.colorize(),
        winston.format.simple()
      ),
    })`;
            }
            else if (transport.type === 'file') {
                return `new winston.transports.File({
      filename: '${transport.config?.filename || 'logs/app.log'}',
      maxsize: ${transport.config?.maxsize || 5242880},
      maxFiles: ${transport.config?.maxFiles || 5},
    })`;
            }
            else if (transport.type === 'http') {
                return `new winston.transports.Http({
      host: '${transport.config?.host || 'localhost'}',
      port: ${transport.config?.port || 3000},
      path: '${transport.config?.path || '/logs'}',
    })`;
            }
            return '';
        }).filter(Boolean).join(',\n    ');
        return `/**
 * Winston Logging Configuration
 * Auto-generated from enhanced monitoring schema
 */

import winston from 'winston';

export const logger = winston.createLogger({
  level: '${level}',
  format: winston.format.combine(
    winston.format.timestamp(),
    winston.format.errors({ stack: true }),
    winston.format.json()
  ),
  defaultMeta: { service: process.env.SERVICE_NAME || 'api' },
  transports: [
    ${transportCode}
  ],
});

// If not in production, log to console with simpler format
if (process.env.NODE_ENV !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.combine(
      winston.format.colorize(),
      winston.format.simple()
    ),
  }));
}

export default logger;
`;
    }
    generatePinoConfig(logging) {
        const level = logging?.level || 'info';
        return `/**
 * Pino Logging Configuration
 * Auto-generated from enhanced monitoring schema
 */

import pino from 'pino';

export const logger = pino({
  level: '${level}',
  transport: process.env.NODE_ENV !== 'production' ? {
    target: 'pino-pretty',
    options: {
      colorize: true,
    },
  } : undefined,
});

export default logger;
`;
    }
    generateBunyanConfig(logging) {
        const level = logging?.level || 'info';
        return `/**
 * Bunyan Logging Configuration
 * Auto-generated from enhanced monitoring schema
 */

import bunyan from 'bunyan';

export const logger = bunyan.createLogger({
  name: process.env.SERVICE_NAME || 'api',
  level: '${level}',
  streams: [
    {
      level: '${level}',
      stream: process.stdout,
    },
  ],
});

export default logger;
`;
    }
    generateGenericLoggingConfig(logging) {
        return `/**
 * Logging Configuration
 * Auto-generated from enhanced monitoring schema
 * Provider: ${logging?.provider}
 */

// TODO: Implement ${logging?.provider} logging configuration
// Log level: ${logging?.level}

export const logger = {
  debug: (...args: any[]) => console.debug(...args),
  info: (...args: any[]) => console.info(...args),
  warn: (...args: any[]) => console.warn(...args),
  error: (...args: any[]) => console.error(...args),
};

export default logger;
`;
    }
    /**
     * Generate logger setup/initialization
     */
    generateLoggerSetup(componentDir, logging) {
        return {
            path: path.join(componentDir, 'src/utils/logger.ts'),
            content: `/**
 * Logger Utility
 * Centralized logging with ${logging?.provider || 'winston'}
 */

import logger from '../config/logging';

export { logger };

// Utility functions for structured logging
export const logRequest = (method: string, url: string, duration: number) => {
  logger.info('HTTP Request', {
    method,
    url,
    duration,
  });
};

export const logError = (error: Error, context?: Record<string, any>) => {
  logger.error('Error occurred', {
    message: error.message,
    stack: error.stack,
    ...context,
  });
};

export const logMetric = (name: string, value: number, tags?: Record<string, string>) => {
  logger.info('Metric', {
    metric: name,
    value,
    tags,
  });
};

export default logger;
`,
            overwrite: false,
        };
    }
    /**
     * Generate error tracking setup
     */
    generateErrorTrackingSetup(componentDir, errorTracking) {
        const provider = errorTracking?.provider || 'sentry';
        let content = '';
        if (provider === 'sentry') {
            content = this.generateSentrySetup();
        }
        else if (provider === 'bugsnag') {
            content = this.generateBugsnagSetup();
        }
        else if (provider === 'rollbar') {
            content = this.generateRollbarSetup();
        }
        else {
            content = this.generateGenericErrorTracking(provider);
        }
        return {
            path: path.join(componentDir, 'src/config/error-tracking.ts'),
            content,
            overwrite: false,
        };
    }
    generateSentrySetup() {
        return `/**
 * Sentry Error Tracking Configuration
 * Auto-generated from enhanced monitoring schema
 */

import * as Sentry from '@sentry/node';
import { ProfilingIntegration } from '@sentry/profiling-node';

export function initializeErrorTracking() {
  Sentry.init({
    dsn: process.env.SENTRY_DSN,
    environment: process.env.NODE_ENV || 'development',
    integrations: [
      new ProfilingIntegration(),
    ],
    // Set sampling rates
    tracesSampleRate: parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE || '0.1'),
    profilesSampleRate: parseFloat(process.env.SENTRY_PROFILES_SAMPLE_RATE || '0.1'),
  });
}

export function captureError(error: Error, context?: Record<string, any>) {
  Sentry.captureException(error, {
    extra: context,
  });
}

export function captureMessage(message: string, level: Sentry.SeverityLevel = 'info') {
  Sentry.captureMessage(message, level);
}

export { Sentry };
`;
    }
    generateBugsnagSetup() {
        return `/**
 * Bugsnag Error Tracking Configuration
 * Auto-generated from enhanced monitoring schema
 */

import Bugsnag from '@bugsnag/js';

export function initializeErrorTracking() {
  Bugsnag.start({
    apiKey: process.env.BUGSNAG_API_KEY || '',
    releaseStage: process.env.NODE_ENV || 'development',
  });
}

export function captureError(error: Error, context?: Record<string, any>) {
  Bugsnag.notify(error, (event) => {
    if (context) {
      event.addMetadata('context', context);
    }
  });
}

export { Bugsnag };
`;
    }
    generateRollbarSetup() {
        return `/**
 * Rollbar Error Tracking Configuration
 * Auto-generated from enhanced monitoring schema
 */

import Rollbar from 'rollbar';

export const rollbar = new Rollbar({
  accessToken: process.env.ROLLBAR_ACCESS_TOKEN,
  environment: process.env.NODE_ENV || 'development',
  captureUncaught: true,
  captureUnhandledRejections: true,
});

export function initializeErrorTracking() {
  // Rollbar is initialized on import
}

export function captureError(error: Error, context?: Record<string, any>) {
  rollbar.error(error, context);
}

export { rollbar as Rollbar };
`;
    }
    generateGenericErrorTracking(provider) {
        return `/**
 * Error Tracking Configuration
 * Provider: ${provider}
 * Auto-generated from enhanced monitoring schema
 */

// TODO: Implement ${provider} error tracking

export function initializeErrorTracking() {
  console.log('Error tracking initialized: ${provider}');
}

export function captureError(error: Error, context?: Record<string, any>) {
  console.error('Error captured:', error, context);
}
`;
    }
    /**
     * Generate APM setup
     */
    generateAPMSetup(componentDir, apm) {
        const provider = apm?.provider || 'datadog';
        let content = '';
        if (provider === 'datadog') {
            content = this.generateDatadogAPM();
        }
        else if (provider === 'new_relic') {
            content = this.generateNewRelicAPM();
        }
        else if (provider === 'app_insights') {
            content = this.generateAppInsightsAPM();
        }
        else {
            content = this.generateGenericAPM(provider);
        }
        return {
            path: path.join(componentDir, 'src/config/apm.ts'),
            content,
            overwrite: false,
        };
    }
    generateDatadogAPM() {
        return `/**
 * Datadog APM Configuration
 * Auto-generated from enhanced monitoring schema
 */

import tracer from 'dd-trace';

export function initializeAPM() {
  tracer.init({
    env: process.env.DD_ENV || process.env.NODE_ENV,
    service: process.env.DD_SERVICE || 'api',
    version: process.env.DD_VERSION || '1.0.0',
    logInjection: true,
  });
}

export { tracer };
`;
    }
    generateNewRelicAPM() {
        return `/**
 * New Relic APM Configuration
 * Auto-generated from enhanced monitoring schema
 */

import newrelic from 'newrelic';

export function initializeAPM() {
  // New Relic auto-instruments when imported
  console.log('New Relic APM initialized');
}

export { newrelic };
`;
    }
    generateAppInsightsAPM() {
        return `/**
 * Azure Application Insights Configuration
 * Auto-generated from enhanced monitoring schema
 */

import * as appInsights from 'applicationinsights';

export function initializeAPM() {
  appInsights.setup(process.env.APPINSIGHTS_INSTRUMENTATIONKEY)
    .setAutoDependencyCorrelation(true)
    .setAutoCollectRequests(true)
    .setAutoCollectPerformance(true, true)
    .setAutoCollectExceptions(true)
    .setAutoCollectDependencies(true)
    .setAutoCollectConsole(true)
    .setUseDiskRetryCaching(true)
    .setSendLiveMetrics(true)
    .start();
}

export const client = appInsights.defaultClient;
`;
    }
    generateGenericAPM(provider) {
        return `/**
 * APM Configuration
 * Provider: ${provider}
 * Auto-generated from enhanced monitoring schema
 */

// TODO: Implement ${provider} APM

export function initializeAPM() {
  console.log('APM initialized: ${provider}');
}
`;
    }
    /**
     * Generate distributed tracing setup
     */
    generateTracingSetup(componentDir, tracing) {
        const provider = tracing?.provider || 'jaeger';
        const samplingRate = tracing?.sampling_rate || 0.1;
        return {
            path: path.join(componentDir, 'src/config/tracing.ts'),
            content: `/**
 * Distributed Tracing Configuration
 * Provider: ${provider}
 * Sampling Rate: ${samplingRate}
 * Auto-generated from enhanced monitoring schema
 */

// TODO: Implement ${provider} distributed tracing
// Sampling rate: ${samplingRate}

export function initializeTracing() {
  console.log('Tracing initialized: ${provider}');
}
`,
            overwrite: false,
        };
    }
    /**
     * Generate metrics setup
     */
    generateMetricsSetup(componentDir, metrics) {
        const trackedMetrics = metrics?.tracked || [];
        const customMetrics = metrics?.custom_metrics || [];
        const metricDefinitions = customMetrics.map(metric => {
            return `export const ${metric.name} = new ${metric.type === 'counter' ? 'Counter' : metric.type === 'gauge' ? 'Gauge' : 'Histogram'}({
  name: '${metric.name}',
  help: '${metric.description}',
});`;
        }).join('\n\n');
        return {
            path: path.join(componentDir, 'src/config/metrics.ts'),
            content: `/**
 * Metrics Configuration
 * Auto-generated from enhanced monitoring schema
 */

// Tracked metrics: ${trackedMetrics.join(', ')}

// Custom metric definitions
${metricDefinitions || '// No custom metrics defined'}

export function initializeMetrics() {
  console.log('Metrics initialized');
}
`,
            overwrite: false,
        };
    }
    /**
     * Generate frontend error tracking
     */
    generateFrontendErrorTracking(componentDir, errorTracking) {
        const provider = errorTracking?.provider || 'sentry';
        return {
            path: path.join(componentDir, 'src/utils/error-tracking.ts'),
            content: `/**
 * Frontend Error Tracking
 * Provider: ${provider}
 * Auto-generated from enhanced monitoring schema
 */

import * as Sentry from '@sentry/react';

export function initializeErrorTracking() {
  Sentry.init({
    dsn: import.meta.env.VITE_SENTRY_DSN,
    environment: import.meta.env.MODE || 'development',
    integrations: [
      new Sentry.BrowserTracing(),
      new Sentry.Replay(),
    ],
    tracesSampleRate: 0.1,
    replaysSessionSampleRate: 0.1,
    replaysOnErrorSampleRate: 1.0,
  });
}

export { Sentry };
`,
            overwrite: false,
        };
    }
    /**
     * Generate frontend APM
     */
    generateFrontendAPM(componentDir, apm) {
        return {
            path: path.join(componentDir, 'src/utils/performance.ts'),
            content: `/**
 * Frontend Performance Monitoring
 * Provider: ${apm?.provider}
 * Auto-generated from enhanced monitoring schema
 */

export function trackPageLoad() {
  if (window.performance) {
    const perfData = window.performance.timing;
    const loadTime = perfData.loadEventEnd - perfData.navigationStart;
    console.log('Page load time:', loadTime, 'ms');

    // TODO: Send to APM provider
  }
}

export function trackUserInteraction(action: string, duration: number) {
  console.log('User interaction:', action, duration, 'ms');
  // TODO: Send to APM provider
}
`,
            overwrite: false,
        };
    }
    /**
     * Generate alert configuration
     */
    generateAlertConfig(outputDir, alerts) {
        const alertDefinitions = alerts?.map(alert => {
            return `{
  name: '${alert.name}',
  condition: '${alert.condition}',
  channels: [${alert.channels.map(c => `'${c}'`).join(', ')}],
  severity: '${alert.severity || 'warning'}',
}`;
        }).join(',\n  ');
        return {
            path: path.join(outputDir, 'alerts.config.ts'),
            content: `/**
 * Alert Definitions
 * Auto-generated from enhanced monitoring schema
 */

export const alerts = [
  ${alertDefinitions}
];

export default alerts;
`,
            overwrite: false,
        };
    }
}
exports.EnhancedMonitoringGenerator = EnhancedMonitoringGenerator;
//# sourceMappingURL=enhanced-monitoring-generator.js.map