// 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 queue validation fails (retryable or not)
   */
  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. Throw in every case so the error reaches the workflow's
    // per-class handler. Laundering a failure into a "no vulnerabilities" decision
    // would render an un-assessed class as clean. Retryable vs non-retryable is
    // decided downstream at the activity boundary.
    const error = result.error;
    logger.warn(`${vulnType}: ${error.message}${error.retryable ? ' (retryable)' : ' (non-retryable, failing class)'}`);
    throw error;
  }
}
