"use strict";
/**
 * Enhanced Analytics Configuration Generator
 *
 * Generates comprehensive analytics infrastructure with support for:
 * - Multi-provider analytics (Mixpanel, Amplitude, Segment, Google Analytics)
 * - Event tracking and management
 * - Funnel and cohort analysis
 * - Custom event definitions
 * - Backend and frontend integration
 * - Privacy and GDPR compliance
 */
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.EnhancedAnalyticsGenerator = void 0;
const path = __importStar(require("path"));
class EnhancedAnalyticsGenerator {
    id = 'enhanced-analytics';
    name = 'Enhanced Analytics Configuration Generator';
    description = 'Generates comprehensive analytics infrastructure with multi-provider support';
    generate(context) {
        const { workflow, outputDirectory } = context;
        const files = [];
        if (!workflow.analytics) {
            return { files };
        }
        const analytics = workflow.analytics;
        // Support both providers array (new) and provider string (old schema)
        const providers = analytics.providers || [{ name: analytics.provider }];
        // Generate provider-specific configurations
        providers.forEach((provider) => {
            const providerName = provider.name || provider;
            if (providerName === 'mixpanel') {
                files.push({
                    path: path.join(outputDirectory, 'analytics/src/providers/mixpanel.ts'),
                    content: this.generateMixpanelProvider(provider),
                });
            }
            else if (providerName === 'amplitude') {
                files.push({
                    path: path.join(outputDirectory, 'analytics/src/providers/amplitude.ts'),
                    content: this.generateAmplitudeProvider(provider),
                });
            }
            else if (providerName === 'segment') {
                files.push({
                    path: path.join(outputDirectory, 'analytics/src/providers/segment.ts'),
                    content: this.generateSegmentProvider(provider),
                });
            }
            else if (providerName === 'google_analytics') {
                files.push({
                    path: path.join(outputDirectory, 'analytics/src/providers/google-analytics.ts'),
                    content: this.generateGoogleAnalyticsProvider(provider),
                });
            }
        });
        // Generate unified analytics service
        files.push({
            path: path.join(outputDirectory, 'analytics/src/services/analytics.ts'),
            content: this.generateAnalyticsService(providers),
        });
        // Generate event definitions
        const events = analytics.events || analytics.tracking?.custom_events;
        if (events) {
            files.push({
                path: path.join(outputDirectory, 'analytics/src/events/definitions.ts'),
                content: this.generateEventDefinitions(events),
            });
            files.push({
                path: path.join(outputDirectory, 'analytics/src/events/tracker.ts'),
                content: this.generateEventTracker(),
            });
        }
        // Generate funnel tracking
        if (analytics.funnels) {
            files.push({
                path: path.join(outputDirectory, 'analytics/src/funnels/definitions.ts'),
                content: this.generateFunnelDefinitions(analytics.funnels),
            });
            files.push({
                path: path.join(outputDirectory, 'analytics/src/funnels/tracker.ts'),
                content: this.generateFunnelTracker(),
            });
        }
        // Generate cohort analysis
        if (analytics.cohorts) {
            files.push({
                path: path.join(outputDirectory, 'analytics/src/cohorts/definitions.ts'),
                content: this.generateCohortDefinitions(analytics.cohorts),
            });
            files.push({
                path: path.join(outputDirectory, 'analytics/src/cohorts/analyzer.ts'),
                content: this.generateCohortAnalyzer(),
            });
        }
        // Generate user properties tracking
        files.push({
            path: path.join(outputDirectory, 'analytics/src/services/user-properties.ts'),
            content: this.generateUserPropertiesService(),
        });
        // Generate privacy and consent management
        const privacy = analytics.privacy;
        if (privacy?.gdpr_compliance) {
            files.push({
                path: path.join(outputDirectory, 'analytics/src/privacy/consent.ts'),
                content: this.generateConsentManager(),
            });
        }
        // Generate frontend integration
        files.push({
            path: path.join(outputDirectory, 'web/src/hooks/useAnalytics.ts'),
            content: this.generateAnalyticsHook(),
        });
        files.push({
            path: path.join(outputDirectory, 'web/src/hooks/useTrackEvent.ts'),
            content: this.generateTrackEventHook(),
        });
        files.push({
            path: path.join(outputDirectory, 'web/src/hooks/useTrackPage.ts'),
            content: this.generateTrackPageHook(),
        });
        files.push({
            path: path.join(outputDirectory, 'web/src/components/AnalyticsProvider.tsx'),
            content: this.generateAnalyticsProvider(),
        });
        // Generate backend integration
        files.push({
            path: path.join(outputDirectory, 'api/src/services/analytics.ts'),
            content: this.generateBackendAnalyticsService(),
        });
        files.push({
            path: path.join(outputDirectory, 'api/src/middleware/analytics.ts'),
            content: this.generateAnalyticsMiddleware(),
        });
        // Generate types
        files.push({
            path: path.join(outputDirectory, 'analytics/src/types/analytics.ts'),
            content: this.generateAnalyticsTypes(),
        });
        // Generate configuration
        files.push({
            path: path.join(outputDirectory, 'analytics/src/config/analytics.ts'),
            content: this.generateAnalyticsConfig(analytics),
        });
        // Generate documentation
        files.push({
            path: path.join(outputDirectory, 'analytics/README.md'),
            content: this.generateAnalyticsDocumentation(analytics),
        });
        return { files };
    }
    generateMixpanelProvider(provider) {
        return `/**
 * Mixpanel Analytics Provider
 */

import mixpanel from 'mixpanel-browser';
import type { AnalyticsProvider, TrackEventParams, IdentifyParams } from '../types/analytics';

export class MixpanelProvider implements AnalyticsProvider {
  private initialized = false;

  async initialize(): Promise<void> {
    if (this.initialized) return;

    const token = process.env.NEXT_PUBLIC_MIXPANEL_TOKEN || process.env.MIXPANEL_TOKEN;
    if (!token) {
      throw new Error('Mixpanel token not configured');
    }

    mixpanel.init(token, {
      debug: process.env.NODE_ENV === 'development',
      track_pageview: ${provider.auto_page_tracking !== false},
      persistence: '${provider.persistence || 'localStorage'}',
    });

    this.initialized = true;
  }

  async trackEvent(params: TrackEventParams): Promise<void> {
    mixpanel.track(params.name, params.properties);
  }

  async identify(params: IdentifyParams): Promise<void> {
    mixpanel.identify(params.userId);

    if (params.properties) {
      mixpanel.people.set(params.properties);
    }
  }

  async setUserProperties(properties: Record<string, any>): Promise<void> {
    mixpanel.people.set(properties);
  }

  async incrementUserProperty(property: string, value: number = 1): Promise<void> {
    mixpanel.people.increment(property, value);
  }

  async trackRevenue(amount: number, properties?: Record<string, any>): Promise<void> {
    mixpanel.people.track_charge(amount, properties);
  }

  async reset(): Promise<void> {
    mixpanel.reset();
  }
}
`;
    }
    generateAmplitudeProvider(provider) {
        return `/**
 * Amplitude Analytics Provider
 */

import * as amplitude from '@amplitude/analytics-browser';
import type { AnalyticsProvider, TrackEventParams, IdentifyParams } from '../types/analytics';

export class AmplitudeProvider implements AnalyticsProvider {
  private initialized = false;

  async initialize(): Promise<void> {
    if (this.initialized) return;

    const apiKey = process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY || process.env.AMPLITUDE_API_KEY;
    if (!apiKey) {
      throw new Error('Amplitude API key not configured');
    }

    amplitude.init(apiKey, {
      defaultTracking: {
        sessions: ${provider.session_tracking !== false},
        pageViews: ${provider.auto_page_tracking !== false},
        formInteractions: ${provider.form_tracking === true},
        fileDownloads: ${provider.file_tracking === true},
      },
    });

    this.initialized = true;
  }

  async trackEvent(params: TrackEventParams): Promise<void> {
    amplitude.track(params.name, params.properties);
  }

  async identify(params: IdentifyParams): Promise<void> {
    const identifyEvent = new amplitude.Identify();

    if (params.properties) {
      Object.entries(params.properties).forEach(([key, value]) => {
        identifyEvent.set(key, value);
      });
    }

    amplitude.identify(identifyEvent);
    amplitude.setUserId(params.userId);
  }

  async setUserProperties(properties: Record<string, any>): Promise<void> {
    const identifyEvent = new amplitude.Identify();

    Object.entries(properties).forEach(([key, value]) => {
      identifyEvent.set(key, value);
    });

    amplitude.identify(identifyEvent);
  }

  async incrementUserProperty(property: string, value: number = 1): Promise<void> {
    const identifyEvent = new amplitude.Identify();
    identifyEvent.add(property, value);
    amplitude.identify(identifyEvent);
  }

  async reset(): Promise<void> {
    amplitude.reset();
  }
}
`;
    }
    generateSegmentProvider(_provider) {
        return `/**
 * Segment Analytics Provider
 */

import { AnalyticsBrowser } from '@segment/analytics-next';
import type { AnalyticsProvider, TrackEventParams, IdentifyParams } from '../types/analytics';

export class SegmentProvider implements AnalyticsProvider {
  private analytics: AnalyticsBrowser | null = null;
  private initialized = false;

  async initialize(): Promise<void> {
    if (this.initialized) return;

    const writeKey = process.env.NEXT_PUBLIC_SEGMENT_WRITE_KEY || process.env.SEGMENT_WRITE_KEY;
    if (!writeKey) {
      throw new Error('Segment write key not configured');
    }

    this.analytics = AnalyticsBrowser.load({ writeKey });
    this.initialized = true;
  }

  async trackEvent(params: TrackEventParams): Promise<void> {
    if (!this.analytics) throw new Error('Segment not initialized');

    await this.analytics.track(params.name, params.properties);
  }

  async identify(params: IdentifyParams): Promise<void> {
    if (!this.analytics) throw new Error('Segment not initialized');

    await this.analytics.identify(params.userId, params.properties);
  }

  async setUserProperties(properties: Record<string, any>): Promise<void> {
    if (!this.analytics) throw new Error('Segment not initialized');

    const userId = await this.analytics.user().id();
    if (userId) {
      await this.analytics.identify(userId, properties);
    }
  }

  async trackPage(name?: string, properties?: Record<string, any>): Promise<void> {
    if (!this.analytics) throw new Error('Segment not initialized');

    await this.analytics.page(name, properties);
  }

  async reset(): Promise<void> {
    if (!this.analytics) throw new Error('Segment not initialized');

    await this.analytics.reset();
  }
}
`;
    }
    generateGoogleAnalyticsProvider(provider) {
        return `/**
 * Google Analytics Provider
 */

import ReactGA from 'react-ga4';
import type { AnalyticsProvider, TrackEventParams, IdentifyParams } from '../types/analytics';

export class GoogleAnalyticsProvider implements AnalyticsProvider {
  private initialized = false;

  async initialize(): Promise<void> {
    if (this.initialized) return;

    const measurementId = process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID || process.env.GA_MEASUREMENT_ID;
    if (!measurementId) {
      throw new Error('Google Analytics measurement ID not configured');
    }

    ReactGA.initialize(measurementId, {
      gtagOptions: {
        send_page_view: ${provider.auto_page_tracking !== false},
      },
    });

    this.initialized = true;
  }

  async trackEvent(params: TrackEventParams): Promise<void> {
    ReactGA.event({
      category: params.properties?.category || 'general',
      action: params.name,
      label: params.properties?.label,
      value: params.properties?.value,
      ...params.properties,
    });
  }

  async identify(params: IdentifyParams): Promise<void> {
    ReactGA.set({ userId: params.userId });

    if (params.properties) {
      ReactGA.set(params.properties);
    }
  }

  async setUserProperties(properties: Record<string, any>): Promise<void> {
    ReactGA.set(properties);
  }

  async trackPage(path: string, title?: string): Promise<void> {
    ReactGA.send({ hitType: 'pageview', page: path, title });
  }

  async reset(): Promise<void> {
    // Google Analytics doesn't have a built-in reset
    // Clear user ID
    ReactGA.set({ userId: null });
  }
}
`;
    }
    generateAnalyticsService(providers) {
        const providerImports = providers
            .map(p => {
            const className = p.name
                .split('_')
                .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
                .join('');
            return `import { ${className}Provider } from '../providers/${p.name.replace(/_/g, '-')}';`;
        })
            .join('\n');
        const providerInstances = providers
            .map(p => {
            const className = p.name
                .split('_')
                .map((w) => w.charAt(0).toUpperCase() + w.slice(1))
                .join('');
            return `  private ${p.name}Provider = new ${className}Provider();`;
        })
            .join('\n');
        return `/**
 * Unified Analytics Service
 *
 * Provides a single interface for tracking across multiple analytics providers
 */

${providerImports}
import type { TrackEventParams, IdentifyParams } from '../types/analytics';

export class AnalyticsService {
${providerInstances}
  private providers: any[] = [];
  private initialized = false;

  async initialize(): Promise<void> {
    if (this.initialized) return;

    this.providers = [
${providers.map(p => `      this.${p.name}Provider,`).join('\n')}
    ];

    await Promise.all(this.providers.map(p => p.initialize()));
    this.initialized = true;
  }

  async trackEvent(params: TrackEventParams): Promise<void> {
    if (!this.initialized) {
      await this.initialize();
    }

    await Promise.all(
      this.providers.map(provider =>
        provider.trackEvent(params).catch((err: Error) => {
          console.error(\`Analytics provider error: \${err.message}\`);
        })
      )
    );
  }

  async identify(params: IdentifyParams): Promise<void> {
    if (!this.initialized) {
      await this.initialize();
    }

    await Promise.all(
      this.providers.map(provider =>
        provider.identify(params).catch((err: Error) => {
          console.error(\`Analytics provider error: \${err.message}\`);
        })
      )
    );
  }

  async setUserProperties(properties: Record<string, any>): Promise<void> {
    if (!this.initialized) {
      await this.initialize();
    }

    await Promise.all(
      this.providers.map(provider =>
        provider.setUserProperties?.(properties).catch((err: Error) => {
          console.error(\`Analytics provider error: \${err.message}\`);
        })
      )
    );
  }

  async trackPage(path: string, title?: string): Promise<void> {
    if (!this.initialized) {
      await this.initialize();
    }

    await Promise.all(
      this.providers.map(provider =>
        provider.trackPage?.(path, title).catch((err: Error) => {
          console.error(\`Analytics provider error: \${err.message}\`);
        })
      )
    );
  }

  async reset(): Promise<void> {
    await Promise.all(
      this.providers.map(provider =>
        provider.reset().catch((err: Error) => {
          console.error(\`Analytics provider error: \${err.message}\`);
        })
      )
    );
  }
}

export const analytics = new AnalyticsService();
`;
    }
    generateEventDefinitions(events) {
        const eventTypes = events.map(e => {
            const properties = e.properties || [];
            const propsType = Array.isArray(properties)
                ? properties.map(key => `  ${key}: string;`).join('\n')
                : Object.entries(properties).map(([key, type]) => `  ${key}: ${type};`).join('\n');
            return `export interface ${e.name}EventProperties {
${propsType}
}`;
        }).join('\n\n');
        const eventNames = events.map(e => `  ${e.name} = '${e.name}',`).join('\n');
        return `/**
 * Analytics Event Definitions
 */

${eventTypes}

export enum EventName {
${eventNames}
}

export type EventProperties =
${events.map(e => `  | { name: EventName.${e.name}; properties: ${e.name}EventProperties }`).join('\n')};
`;
    }
    generateEventTracker() {
        return `/**
 * Type-safe Event Tracker
 */

import { analytics } from '../services/analytics';
import type { EventProperties } from './definitions';

export class EventTracker {
  async track<T extends EventProperties>(event: T): Promise<void> {
    await analytics.trackEvent({
      name: event.name,
      properties: event.properties,
    });
  }

  async trackWithContext<T extends EventProperties>(
    event: T,
    context: Record<string, any>
  ): Promise<void> {
    await analytics.trackEvent({
      name: event.name,
      properties: {
        ...event.properties,
        ...context,
      },
    });
  }
}

export const eventTracker = new EventTracker();
`;
    }
    generateFunnelDefinitions(funnels) {
        const funnelTypes = funnels.map(f => {
            const steps = f.steps.map((s, i) => `  step${i + 1}: '${s.event}',`).join('\n');
            return `export const ${f.name}Funnel = {
  name: '${f.name}',
  steps: {
${steps}
  },
} as const;`;
        }).join('\n\n');
        return `/**
 * Funnel Definitions
 */

${funnelTypes}

export const funnels = [
${funnels.map(f => `  ${f.name}Funnel,`).join('\n')}
] as const;
`;
    }
    generateFunnelTracker() {
        return `/**
 * Funnel Tracker
 */

import { analytics } from '../services/analytics';

export class FunnelTracker {
  private activeFunnels = new Map<string, { step: number; startTime: number }>();

  async startFunnel(funnelName: string): Promise<void> {
    this.activeFunnels.set(funnelName, {
      step: 0,
      startTime: Date.now(),
    });

    await analytics.trackEvent({
      name: \`\${funnelName}_started\`,
      properties: {
        funnel: funnelName,
        timestamp: new Date().toISOString(),
      },
    });
  }

  async trackStep(funnelName: string, stepName: string, properties?: Record<string, any>): Promise<void> {
    const funnel = this.activeFunnels.get(funnelName);

    if (!funnel) {
      console.warn(\`Funnel \${funnelName} not started\`);
      return;
    }

    funnel.step++;
    const timeInFunnel = Date.now() - funnel.startTime;

    await analytics.trackEvent({
      name: stepName,
      properties: {
        funnel: funnelName,
        step: funnel.step,
        time_in_funnel: timeInFunnel,
        ...properties,
      },
    });
  }

  async completeFunnel(funnelName: string, properties?: Record<string, any>): Promise<void> {
    const funnel = this.activeFunnels.get(funnelName);

    if (!funnel) {
      console.warn(\`Funnel \${funnelName} not started\`);
      return;
    }

    const timeToComplete = Date.now() - funnel.startTime;

    await analytics.trackEvent({
      name: \`\${funnelName}_completed\`,
      properties: {
        funnel: funnelName,
        steps_completed: funnel.step,
        time_to_complete: timeToComplete,
        ...properties,
      },
    });

    this.activeFunnels.delete(funnelName);
  }

  async abandonFunnel(funnelName: string, reason?: string): Promise<void> {
    const funnel = this.activeFunnels.get(funnelName);

    if (!funnel) {
      return;
    }

    const timeInFunnel = Date.now() - funnel.startTime;

    await analytics.trackEvent({
      name: \`\${funnelName}_abandoned\`,
      properties: {
        funnel: funnelName,
        step_abandoned: funnel.step,
        time_in_funnel: timeInFunnel,
        reason,
      },
    });

    this.activeFunnels.delete(funnelName);
  }
}

export const funnelTracker = new FunnelTracker();
`;
    }
    generateCohortDefinitions(cohorts) {
        const cohortTypes = cohorts.map(c => {
            return `export const ${c.name}Cohort = {
  name: '${c.name}',
  description: '${c.description || ''}',
  criteria: ${JSON.stringify(c.criteria, null, 2)},
} as const;`;
        }).join('\n\n');
        return `/**
 * Cohort Definitions
 */

${cohortTypes}

export const cohorts = [
${cohorts.map(c => `  ${c.name}Cohort,`).join('\n')}
] as const;
`;
    }
    generateCohortAnalyzer() {
        return `/**
 * Cohort Analyzer
 */

import { analytics } from '../services/analytics';

export interface CohortMembership {
  cohortName: string;
  joinedAt: Date;
  properties: Record<string, any>;
}

export class CohortAnalyzer {
  private userCohorts = new Map<string, CohortMembership[]>();

  async addUserToCohort(
    userId: string,
    cohortName: string,
    properties?: Record<string, any>
  ): Promise<void> {
    const cohorts = this.userCohorts.get(userId) || [];

    cohorts.push({
      cohortName,
      joinedAt: new Date(),
      properties: properties || {},
    });

    this.userCohorts.set(userId, cohorts);

    await analytics.trackEvent({
      name: 'user_joined_cohort',
      properties: {
        cohort: cohortName,
        ...properties,
      },
    });
  }

  async removeUserFromCohort(userId: string, cohortName: string): Promise<void> {
    const cohorts = this.userCohorts.get(userId);

    if (!cohorts) return;

    const filtered = cohorts.filter(c => c.cohortName !== cohortName);
    this.userCohorts.set(userId, filtered);

    await analytics.trackEvent({
      name: 'user_left_cohort',
      properties: {
        cohort: cohortName,
      },
    });
  }

  getUserCohorts(userId: string): CohortMembership[] {
    return this.userCohorts.get(userId) || [];
  }

  isUserInCohort(userId: string, cohortName: string): boolean {
    const cohorts = this.userCohorts.get(userId) || [];
    return cohorts.some(c => c.cohortName === cohortName);
  }
}

export const cohortAnalyzer = new CohortAnalyzer();
`;
    }
    generateUserPropertiesService() {
        return `/**
 * User Properties Service
 */

import { analytics } from './analytics';

export class UserPropertiesService {
  async setProperties(properties: Record<string, any>): Promise<void> {
    await analytics.setUserProperties(properties);
  }

  async setProperty(key: string, value: any): Promise<void> {
    await analytics.setUserProperties({ [key]: value });
  }

  async incrementProperty(key: string, value: number = 1): Promise<void> {
    // This will work with providers that support incrementing
    await analytics.setUserProperties({
      [key]: { $add: value },
    });
  }

  async appendToList(key: string, value: any): Promise<void> {
    await analytics.setUserProperties({
      [key]: { $append: value },
    });
  }

  async setOnce(properties: Record<string, any>): Promise<void> {
    await analytics.setUserProperties(
      Object.entries(properties).reduce((acc, [key, value]) => {
        acc[key] = { $setOnce: value };
        return acc;
      }, {} as Record<string, any>)
    );
  }
}

export const userProperties = new UserPropertiesService();
`;
    }
    generateConsentManager() {
        return `/**
 * Privacy and Consent Manager
 */

import { analytics } from '../services/analytics';

export interface ConsentPreferences {
  analytics: boolean;
  marketing: boolean;
  functional: boolean;
  timestamp: Date;
}

export class ConsentManager {
  private static STORAGE_KEY = 'analytics_consent';
  private consent: ConsentPreferences | null = null;

  async initialize(): Promise<void> {
    const stored = localStorage.getItem(ConsentManager.STORAGE_KEY);

    if (stored) {
      this.consent = JSON.parse(stored);
    }
  }

  async grantConsent(preferences: Omit<ConsentPreferences, 'timestamp'>): Promise<void> {
    this.consent = {
      ...preferences,
      timestamp: new Date(),
    };

    localStorage.setItem(ConsentManager.STORAGE_KEY, JSON.stringify(this.consent));

    if (preferences.analytics) {
      await analytics.initialize();

      await analytics.trackEvent({
        name: 'consent_granted',
        properties: preferences,
      });
    }
  }

  async revokeConsent(): Promise<void> {
    this.consent = {
      analytics: false,
      marketing: false,
      functional: false,
      timestamp: new Date(),
    };

    localStorage.setItem(ConsentManager.STORAGE_KEY, JSON.stringify(this.consent));

    await analytics.reset();

    await analytics.trackEvent({
      name: 'consent_revoked',
      properties: {},
    });
  }

  hasAnalyticsConsent(): boolean {
    return this.consent?.analytics ?? false;
  }

  hasMarketingConsent(): boolean {
    return this.consent?.marketing ?? false;
  }

  hasFunctionalConsent(): boolean {
    return this.consent?.functional ?? false;
  }

  getConsent(): ConsentPreferences | null {
    return this.consent;
  }

  async updateConsent(updates: Partial<Omit<ConsentPreferences, 'timestamp'>>): Promise<void> {
    if (!this.consent) {
      throw new Error('Consent not initialized');
    }

    this.consent = {
      ...this.consent,
      ...updates,
      timestamp: new Date(),
    };

    localStorage.setItem(ConsentManager.STORAGE_KEY, JSON.stringify(this.consent));

    await analytics.trackEvent({
      name: 'consent_updated',
      properties: updates,
    });
  }
}

export const consentManager = new ConsentManager();
`;
    }
    generateAnalyticsHook() {
        return `/**
 * useAnalytics Hook
 */

import { useCallback } from 'react';
import { analytics } from '@/analytics/services/analytics';
import type { TrackEventParams, IdentifyParams } from '@/analytics/types/analytics';

export function useAnalytics() {
  const trackEvent = useCallback(async (params: TrackEventParams) => {
    await analytics.trackEvent(params);
  }, []);

  const identify = useCallback(async (params: IdentifyParams) => {
    await analytics.identify(params);
  }, []);

  const setUserProperties = useCallback(async (properties: Record<string, any>) => {
    await analytics.setUserProperties(properties);
  }, []);

  const trackPage = useCallback(async (path: string, title?: string) => {
    await analytics.trackPage(path, title);
  }, []);

  const reset = useCallback(async () => {
    await analytics.reset();
  }, []);

  return {
    trackEvent,
    identify,
    setUserProperties,
    trackPage,
    reset,
  };
}
`;
    }
    generateTrackEventHook() {
        return `/**
 * useTrackEvent Hook
 */

import { useCallback } from 'react';
import { useAnalytics } from './useAnalytics';

export function useTrackEvent(eventName: string, defaultProperties?: Record<string, any>) {
  const { trackEvent } = useAnalytics();

  const track = useCallback(
    async (properties?: Record<string, any>) => {
      await trackEvent({
        name: eventName,
        properties: {
          ...defaultProperties,
          ...properties,
        },
      });
    },
    [eventName, defaultProperties, trackEvent]
  );

  return track;
}
`;
    }
    generateTrackPageHook() {
        return `/**
 * useTrackPage Hook
 */

import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { useAnalytics } from './useAnalytics';

export function useTrackPage(title?: string) {
  const pathname = usePathname();
  const { trackPage } = useAnalytics();

  useEffect(() => {
    trackPage(pathname, title);
  }, [pathname, title, trackPage]);
}
`;
    }
    generateAnalyticsProvider() {
        return `/**
 * Analytics Provider Component
 */

'use client';

import { createContext, useContext, useEffect, ReactNode } from 'react';
import { analytics } from '@/analytics/services/analytics';
import { consentManager } from '@/analytics/privacy/consent';

interface AnalyticsContextValue {
  initialized: boolean;
}

const AnalyticsContext = createContext<AnalyticsContextValue>({
  initialized: false,
});

export function AnalyticsProvider({ children }: { children: ReactNode }) {
  useEffect(() => {
    const initializeAnalytics = async () => {
      await consentManager.initialize();

      if (consentManager.hasAnalyticsConsent()) {
        await analytics.initialize();
      }
    };

    initializeAnalytics();
  }, []);

  return (
    <AnalyticsContext.Provider value={{ initialized: true }}>
      {children}
    </AnalyticsContext.Provider>
  );
}

export function useAnalyticsContext() {
  return useContext(AnalyticsContext);
}
`;
    }
    generateBackendAnalyticsService() {
        return `/**
 * Backend Analytics Service
 */

import axios from 'axios';

export interface ServerEventParams {
  userId?: string;
  anonymousId?: string;
  event: string;
  properties?: Record<string, any>;
  timestamp?: Date;
}

export class BackendAnalyticsService {
  async trackEvent(params: ServerEventParams): Promise<void> {
    // Send to analytics providers via their HTTP APIs
    const promises: Promise<any>[] = [];

    // Mixpanel
    if (process.env.MIXPANEL_TOKEN) {
      promises.push(
        axios.post('https://api.mixpanel.com/track', {
          event: params.event,
          properties: {
            ...params.properties,
            distinct_id: params.userId || params.anonymousId,
            token: process.env.MIXPANEL_TOKEN,
            time: params.timestamp?.getTime() || Date.now(),
          },
        })
      );
    }

    // Amplitude
    if (process.env.AMPLITUDE_API_KEY) {
      promises.push(
        axios.post(
          'https://api2.amplitude.com/2/httpapi',
          {
            api_key: process.env.AMPLITUDE_API_KEY,
            events: [
              {
                user_id: params.userId,
                device_id: params.anonymousId,
                event_type: params.event,
                event_properties: params.properties,
                time: params.timestamp?.getTime() || Date.now(),
              },
            ],
          }
        )
      );
    }

    // Segment
    if (process.env.SEGMENT_WRITE_KEY) {
      const auth = Buffer.from(\`\${process.env.SEGMENT_WRITE_KEY}:\`).toString('base64');

      promises.push(
        axios.post(
          'https://api.segment.io/v1/track',
          {
            userId: params.userId,
            anonymousId: params.anonymousId,
            event: params.event,
            properties: params.properties,
            timestamp: params.timestamp?.toISOString() || new Date().toISOString(),
          },
          {
            headers: {
              Authorization: \`Basic \${auth}\`,
            },
          }
        )
      );
    }

    await Promise.allSettled(promises);
  }

  async identify(userId: string, traits?: Record<string, any>): Promise<void> {
    const promises: Promise<any>[] = [];

    // Mixpanel
    if (process.env.MIXPANEL_TOKEN) {
      promises.push(
        axios.post('https://api.mixpanel.com/engage', {
          $token: process.env.MIXPANEL_TOKEN,
          $distinct_id: userId,
          $set: traits,
        })
      );
    }

    // Amplitude
    if (process.env.AMPLITUDE_API_KEY) {
      promises.push(
        axios.post('https://api2.amplitude.com/identify', {
          api_key: process.env.AMPLITUDE_API_KEY,
          identification: {
            user_id: userId,
            user_properties: traits,
          },
        })
      );
    }

    // Segment
    if (process.env.SEGMENT_WRITE_KEY) {
      const auth = Buffer.from(\`\${process.env.SEGMENT_WRITE_KEY}:\`).toString('base64');

      promises.push(
        axios.post(
          'https://api.segment.io/v1/identify',
          {
            userId,
            traits,
            timestamp: new Date().toISOString(),
          },
          {
            headers: {
              Authorization: \`Basic \${auth}\`,
            },
          }
        )
      );
    }

    await Promise.allSettled(promises);
  }
}

export const backendAnalytics = new BackendAnalyticsService();
`;
    }
    generateAnalyticsMiddleware() {
        return `/**
 * Analytics Middleware
 */

import { Request, Response, NextFunction } from 'express';
import { backendAnalytics } from '../services/analytics';

export async function analyticsMiddleware(
  req: Request,
  res: Response,
  next: NextFunction
): Promise<void> {
  // Track API requests
  const startTime = Date.now();

  res.on('finish', async () => {
    const duration = Date.now() - startTime;

    await backendAnalytics.trackEvent({
      userId: (req as any).user?.id,
      event: 'api_request',
      properties: {
        method: req.method,
        path: req.path,
        status: res.statusCode,
        duration,
        userAgent: req.get('user-agent'),
        ip: req.ip,
      },
    });
  });

  next();
}
`;
    }
    generateAnalyticsTypes() {
        return `/**
 * Analytics Type Definitions
 */

export interface AnalyticsProvider {
  initialize(): Promise<void>;
  trackEvent(params: TrackEventParams): Promise<void>;
  identify(params: IdentifyParams): Promise<void>;
  setUserProperties?(properties: Record<string, any>): Promise<void>;
  trackPage?(path: string, title?: string): Promise<void>;
  reset(): Promise<void>;
}

export interface TrackEventParams {
  name: string;
  properties?: Record<string, any>;
}

export interface IdentifyParams {
  userId: string;
  properties?: Record<string, any>;
}

export interface PageViewParams {
  path: string;
  title?: string;
  properties?: Record<string, any>;
}

export interface RevenueParams {
  amount: number;
  currency?: string;
  productId?: string;
  quantity?: number;
  properties?: Record<string, any>;
}
`;
    }
    generateAnalyticsConfig(analytics) {
        const providers = analytics.providers || [{ name: analytics.provider }];
        const events = analytics.events || analytics.tracking?.custom_events || [];
        const funnels = analytics.funnels || [];
        const cohorts = analytics.cohorts || [];
        return `/**
 * Analytics Configuration
 */

export const analyticsConfig = {
  providers: ${JSON.stringify(providers, null, 2)},

  events: ${JSON.stringify(events, null, 2)},

  funnels: ${JSON.stringify(funnels, null, 2)},

  cohorts: ${JSON.stringify(cohorts, null, 2)},

  privacy: ${JSON.stringify(analytics.privacy || {}, null, 2)},

  sampling: {
    rate: ${analytics.sampling?.rate || 1.0},
    enabled: ${analytics.sampling?.enabled !== false},
  },
};
`;
    }
    generateAnalyticsDocumentation(analytics) {
        const providers = analytics.providers || [{ name: analytics.provider }];
        const events = analytics.events || analytics.tracking?.custom_events || [];
        const funnels = analytics.funnels || [];
        return `# Analytics Infrastructure

Comprehensive analytics infrastructure with multi-provider support.

## Providers

This project integrates with the following analytics providers:

${providers.map((p) => `- **${p.name}**: ${p.description || 'Analytics tracking'}`).join('\n')}

## Configuration

### Environment Variables

${providers.map((p) => {
            if (p.name === 'mixpanel') {
                return '- `NEXT_PUBLIC_MIXPANEL_TOKEN`: Mixpanel project token';
            }
            else if (p.name === 'amplitude') {
                return '- `NEXT_PUBLIC_AMPLITUDE_API_KEY`: Amplitude API key';
            }
            else if (p.name === 'segment') {
                return '- `NEXT_PUBLIC_SEGMENT_WRITE_KEY`: Segment write key';
            }
            else if (p.name === 'google_analytics') {
                return '- `NEXT_PUBLIC_GA_MEASUREMENT_ID`: Google Analytics measurement ID';
            }
            return '';
        }).filter(Boolean).join('\n')}

## Usage

### Frontend Tracking

\`\`\`typescript
import { useAnalytics } from '@/hooks/useAnalytics';

function MyComponent() {
  const { trackEvent, identify } = useAnalytics();

  const handleClick = async () => {
    await trackEvent({
      name: 'button_clicked',
      properties: { button: 'cta' },
    });
  };

  return <button onClick={handleClick}>Click Me</button>;
}
\`\`\`

### Backend Tracking

\`\`\`typescript
import { backendAnalytics } from '@/services/analytics';

await backendAnalytics.trackEvent({
  userId: user.id,
  event: 'order_completed',
  properties: {
    orderId: order.id,
    revenue: order.total,
  },
});
\`\`\`

## Events

${events.length > 0 ? events.map((e) => `### ${e.name}\n\n${e.description || ''}\n\n**Properties:**\n${Object.entries(e.properties || {}).map(([key, type]) => `- \`${key}\`: ${type}`).join('\n')}`).join('\n\n') : 'No custom events defined.'}

## Funnels

${funnels.length > 0 ? funnels.map((f) => `### ${f.name}\n\n${f.description || ''}\n\n**Steps:**\n${f.steps.map((s, i) => `${i + 1}. ${s.event}`).join('\n')}`).join('\n\n') : 'No funnels defined.'}

## Privacy and Consent

This analytics implementation includes GDPR-compliant consent management:

\`\`\`typescript
import { consentManager } from '@/analytics/privacy/consent';

// Grant consent
await consentManager.grantConsent({
  analytics: true,
  marketing: false,
  functional: true,
});

// Check consent
if (consentManager.hasAnalyticsConsent()) {
  // Track events
}

// Revoke consent
await consentManager.revokeConsent();
\`\`\`

## License

Generated by Bangstack
`;
    }
}
exports.EnhancedAnalyticsGenerator = EnhancedAnalyticsGenerator;
//# sourceMappingURL=enhanced-analytics-generator.js.map