// Extension Analysis Detector - Analyzes file extensions for malicious types

import { BaseDetector } from '../base-detector.js';

export class ExtensionAnalysisDetector extends BaseDetector {
  constructor(config = {}) {
    super({
      name: 'extension-analysis',
      category: 'resource',
      version: '1.0.0',
      description: 'Detects suspicious and dangerous file extensions',
      weight: 2,
      severity: 'high',
      ...config
    });
  }

  async detect(target, ruleRegistry) {
    if (!target.url) {
      return this.createResult(false, [], 0);
    }

    const findings = [];
    const extension = this.extractExtension(target.url);

    if (!extension) {
      return this.createResult(false, [], 0);
    }

    const rules = ruleRegistry.getRules('resource', 'extensions');

    if (!rules || !rules.suspicious) {
      return this.createResult(false, [], 0);
    }

    // Check suspicious extensions
    if (rules.suspicious.includes(extension)) {
      const category = this.getExtensionCategory(extension, rules);

      findings.push(this.createFinding({
        pattern: `ext:${extension}`,
        matched: extension,
        description: `Suspicious file extension: ${extension}`,
        severity: this.getExtensionSeverity(extension, rules),
        weight: 2,
        metadata: {
          extension,
          category,
          url: target.url
        }
      }));
    }

    const matched = findings.length > 0;
    const riskScore = findings.reduce((sum, f) => sum + (f.weight || 1), 0);

    return this.createResult(matched, findings, riskScore);
  }

  extractExtension(url) {
    try {
      const urlObj = new URL(url);
      const path = urlObj.pathname;
      const parts = path.split('.');
      if (parts.length > 1) {
        return `.${parts[parts.length - 1].toLowerCase()}`;
      }
    } catch (error) {
      // Invalid URL
    }
    return null;
  }

  getExtensionCategory(extension, rules) {
    if (!rules.categories) return 'unknown';

    for (const [category, extensions] of Object.entries(rules.categories)) {
      if (extensions.includes(extension)) {
        return category;
      }
    }
    return 'unknown';
  }

  getExtensionSeverity(extension, rules) {
    const category = this.getExtensionCategory(extension, rules);

    const severityMap = {
      executable: 'critical',
      script: 'high',
      archive: 'medium',
      document: 'low'
    };

    return severityMap[category] || 'medium';
  }
}
