/**
 * Resource Discovery Service
 * Orchestrates resource discovery across all provider adapters
 */

import { Context } from '../types/context'
import { logger } from '../lib/logger'
import { createAdapters, ResourceNormalizer } from '../adapters/normalizer'
import * as resourceInventoryService from './resource-inventory'

export interface DiscoveryConfig {
  providers: string[]
  interval?: number // Discovery interval in seconds
}

/**
 * Discover resources from all configured adapters
 */
export async function discoverAllResources(context: Context): Promise<number> {
  const normalizer = createAdapters({
    // Configuration would come from environment or database
    proxmox: process.env.PROXMOX_API_URL && process.env.PROXMOX_API_TOKEN
      ? {
          apiUrl: process.env.PROXMOX_API_URL,
          apiToken: process.env.PROXMOX_API_TOKEN,
        }
      : undefined,
    kubernetes: process.env.KUBECONFIG
      ? {
          kubeconfig: process.env.KUBECONFIG,
        }
      : undefined,
    cloudflare: process.env.CLOUDFLARE_API_TOKEN && process.env.CLOUDFLARE_ACCOUNT_ID
      ? {
          apiToken: process.env.CLOUDFLARE_API_TOKEN,
          accountId: process.env.CLOUDFLARE_ACCOUNT_ID,
        }
      : undefined,
  })

  const normalizedResources = await normalizer.discoverAllResources()
  
  let synced = 0
  for (const resource of normalizedResources) {
    try {
      await resourceInventoryService.upsertResourceInventoryItem(context, {
        resourceType: resource.type,
        provider: resource.provider,
        providerId: resource.providerId,
        providerResourceId: resource.providerResourceId,
        name: resource.name,
        region: resource.region,
        siteId: undefined, // Would need to map region to site
        metadata: resource.metadata,
        tags: resource.tags,
      })
      synced++
    } catch (error) {
      logger.error(`Failed to sync resource ${resource.id}`, { error, resourceId: resource.id })
    }
  }

  return synced
}

/**
 * Discover resources from a specific provider
 */
export async function discoverProviderResources(
  context: Context,
  provider: string
): Promise<number> {
  const normalizer = createAdapters({
    // Same config as above
  })

  const resources = await normalizer.discoverResources(provider as any)
  
  let synced = 0
  for (const resource of resources) {
    try {
      await resourceInventoryService.upsertResourceInventoryItem(context, {
        resourceType: resource.type,
        provider: resource.provider,
        providerId: resource.providerId,
        providerResourceId: resource.providerResourceId,
        name: resource.name,
        region: resource.region,
        metadata: resource.metadata,
        tags: resource.tags,
      })
      synced++
    } catch (error) {
      logger.error(`Failed to sync resource ${resource.id}`, { error, resourceId: resource.id })
    }
  }

  return synced
}

/**
 * Start periodic resource discovery
 */
export function startPeriodicDiscovery(
  context: Context,
  config: DiscoveryConfig
): NodeJS.Timeout {
  const interval = (config.interval || 300) * 1000 // Default 5 minutes

  return setInterval(async () => {
    try {
      if (config.providers.length === 0) {
        await discoverAllResources(context)
      } else {
        for (const provider of config.providers) {
          await discoverProviderResources(context, provider)
        }
      }
    } catch (error) {
      logger.error('Resource discovery error', { error })
    }
  }, interval)
}

