import { Injectable, Logger } from '@nestjs/common';
import { NormalizedCampaignInsight } from '../../meta-ads/interfaces/campaign-insight.interface';
import { AnalysisResult, Insight } from '../dto/analysis-result.dto';
import { AiService } from './ai.service';

/**
 * Analytics Service
 * خدمة التحليلات
 * 
 * Performs data processing, rule-based analysis, and insight generation.
 * يقدم معالجة البيانات، التحليل القائم على القواعد، وتوليد الرؤى.
 */
@Injectable()
export class AnalyticsService {
  constructor(
    private readonly aiService: AiService,
  ) {}

  /**
   * Check if a campaign has any historical AI analysis
   */
  async hasAnyAnalysis(campaignId: string): Promise<boolean> {
    return this.aiService.hasAnyAnalysis(campaignId);
  }

  /**
   * Analyze normalized campaign data
   * تحليل بيانات الحملة الموحدة
   */
  async analyzeCampaign(data: NormalizedCampaignInsight): Promise<AnalysisResult> {
    const insights: Insight[] = [];

    // Rule 1: CTR analysis (Creative Weakness) | تحليل نسبة النقر (ضعف التصميم)
    if (data.ctr < 1.0) {
      insights.push({
        type: 'warning',
        code: 'LOW_CTR',
        message: 'Campaign has low CTR (< 1.0%). Design is likely unappealing.',
        recommendation: 'A/B test different thumbnails and headlines. Focus on the first 3 seconds of video content.',
      });
    } else if (data.ctr > 2.5) {
      insights.push({
        type: 'success',
        code: 'HIGH_CTR',
        message: 'Excellent CTR! The ad creative is resonating well.',
        recommendation: 'Consider scaling this creative to similar audiences or increased budget.',
      });
    }

    // Rule 2: CPC analysis (Targeting Error) | تحليل تكلفة النقرة (خطأ استهداف)
    if (data.cpc > 2.0) {
      insights.push({
        type: 'warning',
        code: 'HIGH_CPC',
        message: 'Cost per click is high. You are likely bidding in a competitive or wrong audience.',
        recommendation: 'Narrow down your interest targeting or test Lookalike audiences to lower costs.',
      });
    }

    // Rule 3: Engagement check (Landing Page/Offer Weakness) | فحص التفاعل (ضعف صفحة الهبوط)
    if (data.impressions > 10000 && data.clicks < 50) {
      insights.push({
        type: 'warning',
        code: 'POOR_ENGAGEMENT',
        message: 'High impressions but extremely low clicks. Audience-Offer mismatch.',
        recommendation: 'The offer may not be compelling. Try adding a "Call to Action" or a limited-time discount.',
      });
    }

    // Rule 4: CPM analysis (Market Competitiveness) | تحليل تكلفة الألف ظهور
    if (data.cpm > 15.0) {
      insights.push({
        type: 'warning',
        code: 'EXPENSIVE_AUDIENCE',
        message: 'You are paying a premium for these impressions.',
        recommendation: 'Try broadening your audience age or geography to find cheaper pockets of inventory.',
      });
    }

    // If no warnings, add general info | إذا لم تكن هناك تحذيرات، أضف معلومات عامة
    if (insights.length === 0) {
      insights.push({
        type: 'info',
        code: 'STABLE_PERFORMANCE',
        message: 'Campaign is performing within normal parameters.',
      });
    }

    // AI Enrichment | إغراء التحليل بالذكاء الاصطناعي
    const aiRecommendation = await this.aiService.generateCampaignInsights(data, data.campaignId);

    return {
      campaignId: data.campaignId,
      campaignName: data.campaignName,
      metrics: {
        impressions: data.impressions,
        clicks: data.clicks,
        spend: data.spend,
        ctr: data.ctr,
        cpc: data.cpc,
        cpm: data.cpm,
      },
      insights,
      aiRecommendation,
    };
  }

  /**
   * Batch analysis | تحليل الدفعة
   */
  async analyzeBatch(items: NormalizedCampaignInsight[]): Promise<AnalysisResult[]> {
    return Promise.all(items.map((item) => this.analyzeCampaign(item)));
  }

  /**
   * Analyze ad creative visually using AI Vision
   * تحليل التصميم الإعلاني بصرياً باستخدام رؤية الذكاء الاصطناعي
   */
  async analyzeVisual(
    imageUrl: string, 
    adCopy?: string, 
    metrics?: any, 
    tier: string = 'standard',
    campaignId?: string
  ): Promise<string> {
    return this.aiService.analyzeCreative(imageUrl, { adCopy, metrics }, tier, campaignId);
  }
}
