// Copyright (C) 2025 Keygraph, Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License version 3
// as published by the Free Software Foundation.

/**
 * Exploitation Checker Service
 *
 * Pure domain logic for determining whether exploitation should run.
 * Reads queue file, parses JSON, returns decision.
 *
 * No Temporal dependencies - this is pure business logic.
 */

import type { ActivityLogger } from '../types/activity-logger.js';
import { isOk } from '../types/result.js';
import { type ExploitationDecision, type VulnType, validateQueueSafe } from './queue-validation.js';

/**
 * Service for checking exploitation queue decisions.
 *
 * Determines whether an exploit agent should run based on
 * the vulnerability analysis deliverables and queue files.
 */
export class ExploitationCheckerService {
  /**
   * Check if exploitation should run for a given vulnerability type.
   *
   * Reads the vulnerability queue file and returns the decision.
   * This is pure domain logic - reads queue file, parses JSON, returns decision.
   *
   * @param vulnType - Type of vulnerability (injection, xss, auth, ssrf, authz)
   * @param repoPath - Path to the repository containing deliverables
   * @param logger - ActivityLogger for structured logging
   * @returns ExploitationDecision indicating whether to exploit
   * @throws PentestError if validation fails and is retryable
   */
  async checkQueue(vulnType: VulnType, repoPath: string, logger: ActivityLogger): Promise<ExploitationDecision> {
    const result = await validateQueueSafe(vulnType, repoPath);

    if (isOk(result)) {
      const decision = result.value;
      logger.info(
        `${vulnType}: ${decision.shouldExploit ? `${decision.vulnerabilityCount} vulnerabilities found` : 'no vulnerabilities, skipping exploitation'}`,
      );
      return decision;
    }

    // Validation failed - check if we should retry or skip
    const error = result.error;
    if (error.retryable) {
      // Re-throw retryable errors so caller can handle retry
      logger.warn(`${vulnType}: ${error.message} (retryable)`);
      throw error;
    }

    // Non-retryable error - skip exploitation gracefully
    logger.warn(`${vulnType}: ${error.message}, skipping exploitation`);
    return {
      shouldExploit: false,
      shouldRetry: false,
      vulnerabilityCount: 0,
      vulnType,
    };
  }
}
