/**
 * LocalGreenChain Transparency Module
 *
 * Comprehensive transparency system providing:
 * - Immutable audit logging
 * - Real-time event streaming
 * - Transparency dashboards
 * - Data export & reporting
 * - Digital signatures for verification
 */

export * from './AuditLog';
export * from './EventStream';
export * from './TransparencyDashboard';
export * from './DigitalSignatures';

import { getAuditLog } from './AuditLog';
import { getEventStream } from './EventStream';
import { getTransparencyDashboard } from './TransparencyDashboard';
import { getSignatureManager } from './DigitalSignatures';

/**
 * Initialize all transparency components
 */
export function initializeTransparency(): void {
  console.log('[Transparency] Initializing transparency module...');

  // Initialize components
  const auditLog = getAuditLog();
  const eventStream = getEventStream();
  const dashboard = getTransparencyDashboard();
  const signatures = getSignatureManager();

  // Log initialization
  auditLog.logSystemEvent('Transparency module initialized', 'INFO', {
    components: ['AuditLog', 'EventStream', 'TransparencyDashboard', 'DigitalSignatures']
  });

  // Emit initialization event
  eventStream.emit('system.health', 'transparency', {
    status: 'initialized',
    components: ['AuditLog', 'EventStream', 'TransparencyDashboard', 'DigitalSignatures']
  });

  console.log('[Transparency] Transparency module ready');
}

/**
 * Middleware helper for API routes to log requests
 */
export function createAuditMiddleware() {
  const auditLog = getAuditLog();
  const eventStream = getEventStream();

  return {
    logRequest: (
      endpoint: string,
      method: string,
      actor: { id?: string; ip?: string; userAgent?: string }
    ) => {
      const correlationId = `req_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;

      auditLog.logApiCall(endpoint, method, {
        id: actor.id || 'anonymous',
        type: actor.id ? 'USER' : 'ANONYMOUS',
        ip: actor.ip,
        userAgent: actor.userAgent
      }, {});

      return correlationId;
    },

    logResponse: (
      endpoint: string,
      method: string,
      statusCode: number,
      responseTime: number,
      error?: string
    ) => {
      const severity = error ? 'ERROR' : statusCode >= 400 ? 'WARNING' : 'INFO';

      if (severity !== 'INFO') {
        eventStream.emit('system.alert', 'api', {
          endpoint,
          method,
          statusCode,
          error
        }, { priority: severity === 'ERROR' ? 'HIGH' : 'NORMAL' });
      }
    }
  };
}

/**
 * Quick access to transparency components
 */
export const transparency = {
  get audit() { return getAuditLog(); },
  get events() { return getEventStream(); },
  get dashboard() { return getTransparencyDashboard(); },
  get signatures() { return getSignatureManager(); }
};

export default transparency;
