/**
 * Telemetry Service
 * Unified abstraction layer that routes events to all configured analytics providers.
 *
 * Usage:
 *   import { telemetry } from '@startsimpli/analytics'
 *
 *   // Track an event
 *   telemetry.track('fundraise_created', 'fundraise', { name: 'Series A' })
 *
 *   // Track page view
 *   telemetry.pageView('/dashboard')
 *
 *   // Identify user
 *   telemetry.identify({ userId: '123', email: 'user@example.com' })
 *
 *   // Check feature flags (PostHog)
 *   if (telemetry.isFeatureEnabled('new-dashboard')) { ... }
 */

import { GoogleAnalyticsProvider } from './providers/gtag'
import { PostHogProvider } from './providers/posthog'
import { captureAttribution, type AttributionOptions, type CapturedAttribution } from './attribution'
import type {
  AnalyticsEvent,
  AnalyticsProvider,
  EventCategory,
  FeatureFlagResult,
  PageViewEvent,
  TelemetryConfig,
  UserIdentity,
} from './types'

export class TelemetryService {
  private providers: AnalyticsProvider[] = []
  private posthog: PostHogProvider | null = null
  private googleAnalytics: GoogleAnalyticsProvider | null = null
  private initialized = false
  private debug: boolean
  private enabled: boolean

  constructor() {
    this.debug = process.env.NODE_ENV === 'development'
    this.enabled =
      process.env.NODE_ENV === 'production' ||
      process.env.NEXT_PUBLIC_ANALYTICS_ENABLED === 'true'
  }

  /**
   * Initialize all analytics providers.
   * Call once when the app loads (in a client component).
   *
   * @param config - Optional override for provider configuration.
   *   If not provided, providers are configured from environment variables:
   *   - NEXT_PUBLIC_GA_MEASUREMENT_ID
   *   - NEXT_PUBLIC_POSTHOG_KEY / NEXT_PUBLIC_POSTHOG_HOST
   */
  initialize(config?: Partial<TelemetryConfig>): void {
    if (typeof window === 'undefined') return
    if (this.initialized) return

    const debug = config?.debug ?? this.debug

    // Initialize Google Analytics
    const gaMeasurementId =
      config?.googleAnalytics?.measurementId ||
      process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID ||
      ''

    if (config?.googleAnalytics?.enabled !== false && gaMeasurementId) {
      this.googleAnalytics = new GoogleAnalyticsProvider(gaMeasurementId, debug)
      this.googleAnalytics.initialize()
      if (this.googleAnalytics.initialized) {
        this.providers.push(this.googleAnalytics)
      }
    }

    // Initialize PostHog
    const posthogKey =
      config?.posthog?.apiKey || process.env.NEXT_PUBLIC_POSTHOG_KEY || ''
    const posthogHost =
      config?.posthog?.apiHost ||
      process.env.NEXT_PUBLIC_POSTHOG_HOST ||
      'https://us.i.posthog.com'

    if (config?.posthog?.enabled !== false && posthogKey) {
      this.posthog = new PostHogProvider(posthogKey, posthogHost, debug, config?.posthog?.options)
      this.posthog.initialize()
      // Queued by the provider until posthog-js loads; rides on every event after.
      if (config?.posthog?.superProperties) this.posthog.register(config.posthog.superProperties)
      // PostHog loads asynchronously — always register the provider.
      // The provider's isReady() check handles the async window internally
      // and silently drops the few events that fire before the script loads.
      this.providers.push(this.posthog)
    }

    this.initialized = true

    if (debug) {
      console.log(
        '[Telemetry] Initialized with providers:',
        this.providers.map((p) => p.name).join(', ') || 'none'
      )
    }
  }

  identify(identity: UserIdentity): void {
    if (!this.shouldTrack()) return

    this.providers.forEach((provider) => {
      try {
        provider.identify(identity)
      } catch (error) {
        console.error(`[Telemetry] Error identifying user in ${provider.name}:`, error)
      }
    })

    if (this.debug) console.log('[Telemetry] User identified:', identity.userId)
  }

  reset(): void {
    if (!this.shouldTrack()) return

    this.providers.forEach((provider) => {
      try {
        provider.reset()
      } catch (error) {
        console.error(`[Telemetry] Error resetting in ${provider.name}:`, error)
      }
    })

    if (this.debug) console.log('[Telemetry] User reset')
  }

  track(
    eventName: string,
    category: EventCategory,
    properties?: Record<string, string | number | boolean | null | undefined>
  ): void {
    if (!this.shouldTrack()) return

    const event: AnalyticsEvent = {
      name: eventName,
      category,
      properties,
      timestamp: Date.now(),
    }

    this.providers.forEach((provider) => {
      try {
        provider.trackEvent(event)
      } catch (error) {
        console.error(`[Telemetry] Error tracking event in ${provider.name}:`, error)
      }
    })

    if (this.debug) console.log('[Telemetry] Event tracked:', eventName, properties)
  }

  pageView(
    path: string,
    title?: string,
    properties?: Record<string, string | number | boolean | null | undefined>
  ): void {
    if (!this.shouldTrack()) return

    const pageView: PageViewEvent = {
      path,
      title,
      referrer: typeof document !== 'undefined' ? document.referrer : undefined,
      properties,
    }

    this.providers.forEach((provider) => {
      try {
        provider.trackPageView(pageView)
      } catch (error) {
        console.error(`[Telemetry] Error tracking page view in ${provider.name}:`, error)
      }
    })

    if (this.debug) console.log('[Telemetry] Page view:', path)
  }

  setUserProperties(properties: Record<string, unknown>): void {
    if (!this.shouldTrack()) return

    this.providers.forEach((provider) => {
      try {
        provider.setUserProperties?.(properties)
      } catch (error) {
        console.error(`[Telemetry] Error setting properties in ${provider.name}:`, error)
      }
    })
  }

  getFeatureFlag(
    key: string,
    defaultValue: boolean | string | number = false
  ): FeatureFlagResult {
    if (!this.posthog) {
      return { key, value: defaultValue, source: 'default' }
    }
    return this.posthog.getFeatureFlag(key, defaultValue)
  }

  isFeatureEnabled(key: string): boolean {
    if (!this.posthog) return false
    return this.posthog.isFeatureEnabled(key)
  }

  reloadFeatureFlags(): void {
    this.posthog?.reloadFeatureFlags()
  }

  onFeatureFlags(callback: (flags: string[]) => void): void {
    this.posthog?.onFeatureFlags(callback)
  }

  group(groupType: string, groupKey: string, properties?: Record<string, unknown>): void {
    if (!this.shouldTrack()) return
    this.posthog?.group(groupType, groupKey, properties)
  }

  optIn(): void {
    this.enabled = true
    this.posthog?.optIn()
  }

  optOut(): void {
    this.enabled = false
    this.posthog?.optOut()
  }

  hasOptedOut(): boolean {
    return this.posthog?.hasOptedOut() ?? false
  }

  /**
   * Capture first-touch click ids / utm values / GA ids (see ./attribution) and send them to
   * PostHog: first-touch as `initial_*` super + person properties, this visit's as `latest_*`.
   * No-op without consent, or until initialize() has run.
   */
  captureAttribution(options: AttributionOptions = {}): CapturedAttribution | null {
    if (!this.shouldTrack()) return null
    const captured = captureAttribution({ hasConsent: () => !this.hasOptedOut(), ...options })
    if (!captured || !this.posthog) return captured
    const prefix = (obj: Record<string, unknown>, p: string) =>
      Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined).map(([k, v]) => [`${p}${k}`, v]))
    const first = prefix(captured.firstTouch as Record<string, unknown>, 'initial_')
    this.posthog.register(first, true)
    this.posthog.setPersonPropertiesOnce(first)
    const latest = prefix(captured.latest as Record<string, unknown>, 'latest_')
    if (Object.keys(latest).length) this.posthog.register(latest)
    return captured
  }

  getSessionId(): string | undefined {
    return this.posthog?.getSessionId()
  }

  getPostHog(): PostHogProvider | null {
    return this.posthog
  }

  getGoogleAnalytics(): GoogleAnalyticsProvider | null {
    return this.googleAnalytics
  }

  private shouldTrack(): boolean {
    if (typeof window === 'undefined') return false
    if (!this.initialized) return false
    if (!this.enabled) return false
    return true
  }
}

// Singleton instance
export const telemetry = new TelemetryService()

// Convenience functions
export function trackEvent(
  eventName: string,
  category: EventCategory,
  properties?: Record<string, string | number | boolean | null | undefined>
): void {
  telemetry.track(eventName, category, properties)
}

export function trackPageView(
  path: string,
  title?: string,
  properties?: Record<string, string | number | boolean | null | undefined>
): void {
  telemetry.pageView(path, title, properties)
}

export function identifyUser(identity: UserIdentity): void {
  telemetry.identify(identity)
}

export function resetUser(): void {
  telemetry.reset()
}
