/**
 * Resource Normalization Layer
 * Converts provider-specific resources to unified format
 */

import { InfrastructureAdapter, NormalizedResource } from './types.js'
import { logger } from '../lib/logger'
import { ResourceProvider } from '../types/resource.js'
import { ProxmoxAdapter } from './proxmox/adapter.js'
import { KubernetesAdapter } from './kubernetes/adapter.js'
import { CloudflareAdapter } from './cloudflare/adapter.js'

export class ResourceNormalizer {
  private adapters: Map<ResourceProvider, InfrastructureAdapter> = new Map()

  constructor() {
    // Initialize adapters based on configuration
    // This will be configured via environment variables or config files
  }

  /**
   * Register an adapter for a provider
   */
  registerAdapter(provider: ResourceProvider, adapter: InfrastructureAdapter): void {
    this.adapters.set(provider, adapter)
  }

  /**
   * Get adapter for a provider
   */
  getAdapter(provider: ResourceProvider): InfrastructureAdapter | null {
    return this.adapters.get(provider) || null
  }

  /**
   * Discover resources from all registered adapters
   */
  async discoverAllResources(): Promise<NormalizedResource[]> {
    const allResources: NormalizedResource[] = []

    for (const [provider, adapter] of this.adapters.entries()) {
      try {
        const resources = await adapter.discoverResources()
        allResources.push(...resources)
      } catch (error) {
        logger.error(`Error discovering resources from ${provider}`, { error, provider })
      }
    }

    return allResources
  }

  /**
   * Discover resources from a specific provider
   */
  async discoverResources(provider: ResourceProvider): Promise<NormalizedResource[]> {
    const adapter = this.getAdapter(provider)
    if (!adapter) {
      throw new Error(`No adapter registered for provider: ${provider}`)
    }
    return adapter.discoverResources()
  }

  /**
   * Check health of all adapters
   */
  async checkAllAdaptersHealth(): Promise<Record<ResourceProvider, any>> {
    const health: Record<string, any> = {}

    for (const [provider, adapter] of this.adapters.entries()) {
      try {
        health[provider] = await adapter.healthCheck()
      } catch (error) {
        health[provider] = {
          status: 'unhealthy',
          error: error instanceof Error ? error.message : 'Unknown error',
          lastChecked: new Date(),
        }
      }
    }

    return health
  }
}

// Factory function to create adapters from configuration
export function createAdapters(config: {
  proxmox?: { apiUrl: string; apiToken: string }
  kubernetes?: { kubeconfig?: string; context?: string }
  cloudflare?: { apiToken: string; accountId: string }
}): ResourceNormalizer {
  const normalizer = new ResourceNormalizer()

  if (config.proxmox) {
    normalizer.registerAdapter('PROXMOX', new ProxmoxAdapter(config.proxmox))
  }

  if (config.kubernetes) {
    normalizer.registerAdapter('KUBERNETES', new KubernetesAdapter(config.kubernetes))
  }

  if (config.cloudflare) {
    normalizer.registerAdapter('CLOUDFLARE', new CloudflareAdapter(config.cloudflare))
  }

  return normalizer
}

