/**
 * Prometheus Monitoring Adapter
 * Collects metrics from Prometheus and normalizes them
 */

export interface PrometheusConfig {
  url: string
  username?: string
  password?: string
}

export interface PrometheusQueryResult {
  metric: Record<string, string>
  value: [number, string] // [timestamp, value]
}

export class PrometheusAdapter {
  private config: PrometheusConfig

  constructor(config: PrometheusConfig) {
    this.config = config
  }

  async query(query: string, time?: Date): Promise<PrometheusQueryResult[]> {
    const url = new URL(`${this.config.url}/api/v1/query`)
    if (time) {
      url.searchParams.set('time', (time.getTime() / 1000).toString())
    }
    url.searchParams.set('query', query)

    const headers: Record<string, string> = {}
    if (this.config.username && this.config.password) {
      const auth = Buffer.from(`${this.config.username}:${this.config.password}`).toString('base64')
      headers['Authorization'] = `Basic ${auth}`
    }

    const response = await fetch(url.toString(), { headers })
    const data = await response.json()

    if (data.status === 'success' && data.data?.result) {
      return data.data.result
    }

    return []
  }

  async queryRange(
    query: string,
    start: Date,
    end: Date,
    step: string = '15s'
  ): Promise<PrometheusQueryResult[]> {
    const url = new URL(`${this.config.url}/api/v1/query_range`)
    url.searchParams.set('query', query)
    url.searchParams.set('start', (start.getTime() / 1000).toString())
    url.searchParams.set('end', (end.getTime() / 1000).toString())
    url.searchParams.set('step', step)

    const response = await fetch(url.toString())
    const data = await response.json()

    if (data.status === 'success' && data.data?.result) {
      return data.data.result
    }

    return []
  }

  async getMetrics(resourceId: string, metricType: string, timeRange: { start: Date; end: Date }) {
    // Query Prometheus for resource metrics
    const query = `resource_${metricType.toLowerCase()}{resource_id="${resourceId}"}`
    return this.queryRange(query, timeRange.start, timeRange.end)
  }
}

