/**
 * Diagnostic Trigger Job — Background job for auto-trigger evaluation
 * Runs every 5 minutes to check trigger conditions and auto-start sessions.
 */

import { setInterval } from 'node:timers';
import { runAllTriggers } from './auto-triggers.js';
import { getRegisteredContainer } from '@bytelyst/cosmos';
import type { TriggerConfig } from './auto-triggers.js';

const TRIGGER_CONTAINER = 'diagnostic_triggers';
const EVALUATION_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes

let jobInterval: ReturnType<typeof setInterval> | null = null;

/**
 * Get all unique product IDs that have triggers configured.
 */
async function getProductsWithTriggers(): Promise<string[]> {
  const container = await getRegisteredContainer(TRIGGER_CONTAINER);

  // Query all triggers and extract unique product IDs
  const query = {
    query: 'SELECT DISTINCT c.productId FROM c WHERE c.enabled = true',
  };

  const { resources } = await container.items.query<{ productId: string }>(query).fetchAll();
  return resources.map(r => r.productId);
}

/**
 * Evaluate a single trigger by ID.
 * Used for testing or manual re-evaluation.
 */
export async function evaluateSingleTrigger(
  triggerId: string,
  adminUserId: string
): Promise<{ triggered: boolean; reason?: string; sessionId?: string }> {
  const container = await getRegisteredContainer(TRIGGER_CONTAINER);

  try {
    const { resource } = await container.item(triggerId, triggerId).read<TriggerConfig>();
    if (!resource) {
      return { triggered: false, reason: 'Trigger not found' };
    }

    if (!resource.enabled) {
      return { triggered: false, reason: 'Trigger disabled' };
    }

    const { evaluateTrigger } = await import('./auto-triggers.js');
    const result = await evaluateTrigger(resource, adminUserId);

    return {
      triggered: result.triggered,
      reason: result.reason,
      sessionId: result.session?.id,
    };
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    return { triggered: false, reason: `Error: ${msg}` };
  }
}

/**
 * Run trigger evaluation for all products.
 * Called by the scheduled job.
 */
async function runTriggerEvaluation(log?: { info: (msg: string) => void }): Promise<void> {
  const logger = log || console;

  try {
    logger.info('[diagnostic-trigger-job] Starting trigger evaluation');

    const productIds = await getProductsWithTriggers();
    logger.info(`[diagnostic-trigger-job] Found ${productIds.length} products with enabled triggers`);

    let totalEvaluated = 0;
    let totalTriggered = 0;

    for (const productId of productIds) {
      try {
        // Use system user for auto-triggered evaluations
        const results = await runAllTriggers(productId, 'system');
        totalEvaluated += results.length;
        totalTriggered += results.filter(r => r.triggered).length;

        const triggeredCount = results.filter(r => r.triggered).length;
        if (triggeredCount > 0) {
          logger.info(`[diagnostic-trigger-job] Product ${productId}: ${triggeredCount}/${results.length} triggers fired`);
        }
      } catch (err) {
        const msg = err instanceof Error ? err.message : String(err);
        logger.info(`[diagnostic-trigger-job] Error evaluating triggers for ${productId}: ${msg}`);
      }
    }

    logger.info(`[diagnostic-trigger-job] Evaluation complete: ${totalTriggered}/${totalEvaluated} triggers fired`);
  } catch (err) {
    const msg = err instanceof Error ? err.message : String(err);
    logger.info(`[diagnostic-trigger-job] Fatal error: ${msg}`);
  }
}

/**
 * Start the background trigger evaluation job.
 * Called once at server startup.
 */
export function startTriggerEvaluationJob(log?: { info: (msg: string) => void }): void {
  if (jobInterval) {
    return; // Already running
  }

  const logger = log || console;
  logger.info('[diagnostic-trigger-job] Starting evaluation job (5 minute interval)');

  // Run immediately on startup
  runTriggerEvaluation(log).catch(() => {});

  // Schedule recurring runs
  jobInterval = setInterval(() => {
    runTriggerEvaluation(log).catch(() => {});
  }, EVALUATION_INTERVAL_MS);
}

/**
 * Stop the background trigger evaluation job.
 * Used for graceful shutdown.
 */
export function stopTriggerEvaluationJob(): void {
  if (jobInterval) {
    clearInterval(jobInterval);
    jobInterval = null;
  }
}

/**
 * Get current job status.
 */
export function getTriggerJobStatus(): {
  running: boolean;
  intervalMinutes: number;
} {
  return {
    running: jobInterval !== null,
    intervalMinutes: EVALUATION_INTERVAL_MS / 60000,
  };
}
