import { Injectable, Logger } from '@nestjs/common';
import { WebsiteAnalyzerService } from './services/website-analyzer.service';
import { EnhancedDarkWebScannerService } from './services/darkweb-scanner.service';
import { ScanWebsiteDto } from './dto/scan-website.dto';
import { FindingsResponseDto, FindingDetail } from './dto/findings.dto';

@Injectable()
export class EnhancedScanService {
  private readonly logger = new Logger(EnhancedScanService.name);

  constructor(
    private readonly websiteAnalyzer: WebsiteAnalyzerService,
    private readonly darkWebScanner: EnhancedDarkWebScannerService
  ) {}

  async scanWebsite(dto: ScanWebsiteDto): Promise<FindingsResponseDto> {
    const startTime = Date.now();
    const monitorId = `scan-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;

    this.logger.log(`Starting enhanced scan for ${dto.websiteUrl} with config:`, {
      amount: dto.amount,
      scrapeContent: dto.scrapeContent,
      scrapeImages: dto.scrapeImages,
      debugMode: dto.debugMode
    });

    try {
      // Step 1: Analyze the target website
      const websiteInfo = await this.websiteAnalyzer.analyzeWebsite(dto.websiteUrl);
      
      if (dto.debugMode) {
        this.logger.debug('Website analysis results:', websiteInfo);
      }

      // Step 2: Perform enhanced dark web scan
      const scanConfig = {
        amount: dto.amount || 10,
        scrapeContent: dto.scrapeContent ?? true,
        scrapeImages: dto.scrapeImages ?? false,
        debugMode: dto.debugMode ?? false
      };

      const rawFindings = await this.darkWebScanner.scanForMentions(
        websiteInfo.keywords,
        scanConfig
      );

      if (dto.debugMode) {
        this.logger.debug(`Raw findings count: ${rawFindings.length}`);
      }

      // Step 3: Transform results to match API response format
      const findings: FindingDetail[] = rawFindings.map(finding => ({
        sourceUrl: finding.url,
        title: finding.title,
        context: finding.description,
        keywords: finding.keywords,
        textAnalysis: finding.textAnalysis,
        metadata: finding.metadata,
        linksCount: finding.links?.length,
        emails: finding.emails,
        documents: finding.documents,
        images: finding.images,
        imageGalleryPath: finding.imageGalleryPath,
        discoveredAt: finding.timestamp,
        riskLevel: finding.riskLevel,
        confidence: finding.confidence
      }));

      const executionTime = Date.now() - startTime;

      const response: FindingsResponseDto = {
        monitorId,
        websiteUrl: dto.websiteUrl,
        totalFindings: findings.length,
        scanConfig,
        findings,
        executionTime,
        completedAt: new Date()
      };

      this.logger.log(`Enhanced scan completed for ${dto.websiteUrl} in ${executionTime}ms. Found ${findings.length} results.`);

      return response;

    } catch (error) {
      this.logger.error(`Enhanced scan failed for ${dto.websiteUrl}:`, error.message);
      
      // Return error response in expected format
      return {
        monitorId,
        websiteUrl: dto.websiteUrl,
        totalFindings: 0,
        scanConfig: {
          amount: dto.amount || 10,
          scrapeContent: dto.scrapeContent ?? true,
          scrapeImages: dto.scrapeImages ?? false,
          debugMode: dto.debugMode ?? false
        },
        findings: [],
        executionTime: Date.now() - startTime,
        completedAt: new Date()
      };
    }
  }

  async healthCheck(): Promise<{ status: string; torConnection: boolean; timestamp: Date }> {
    try {
      const torStatus = await this.darkWebScanner.healthCheck();
      
      return {
        status: torStatus ? 'healthy' : 'degraded',
        torConnection: torStatus,
        timestamp: new Date()
      };
    } catch (error) {
      this.logger.error('Health check failed:', error.message);
      
      return {
        status: 'unhealthy',
        torConnection: false,
        timestamp: new Date()
      };
    }
  }
}