import { Controller, Post, Body, UseGuards, UseInterceptors, Headers } from '@nestjs/common';
import { CacheInterceptor } from '@nestjs/cache-manager';
import { ApiTags, ApiOperation, ApiResponse, ApiHeader } from '@nestjs/swagger';
import { AnalyticsService } from '../services/analytics.service';
import { MetaAdsService } from '../../meta-ads/services/meta-ads.service';
import { FetchMetaInsightsDto } from '../../meta-ads/dto/fetch-insights.dto';
import { AnalysisResult } from '../dto/analysis-result.dto';
import { SubscriptionGuard } from '../../auth/guards/subscription.guard';

import { TikTokAdsService } from '../../tiktok-ads/services/tiktok-ads.service';
import { GoogleAdsService } from '../../google-ads/services/google-ads.service';
import { UsersService } from '../../users/services/users.service';

/**
 * Analytics Controller
 * متحكم التحليلات
 * 
 * Exposes endpoints for data analysis and insight retrieval.
 * يوفر نقاط نهاية لتحليل البيانات واسترجاع الرؤى.
 */
import { AnalyzeVisualDto } from '../dto/analyze-visual.dto';

@ApiTags('analytics')
@Controller('analyze')
@UseInterceptors(CacheInterceptor)
export class AnalyticsController {
  constructor(
    private readonly analyticsService: AnalyticsService,
    private readonly metaAdsService: MetaAdsService,
    private readonly tiktokAdsService: TikTokAdsService,
    private readonly googleAdsService: GoogleAdsService,
    private readonly usersService: UsersService,
  ) {}

  @Post('meta')
  @UseGuards(SubscriptionGuard)
  @ApiHeader({ name: 'x-user-id', description: 'User ID for subscription check' })
  @ApiOperation({ summary: 'Fetch from Meta then analyze | الجلب من ميتا ثم التحليل' })
  @ApiResponse({ status: 200, type: [AnalysisResult] })
  async analyzeMeta(
    @Body() dto: FetchMetaInsightsDto,
    @Headers('x-user-id') userId?: string,
  ): Promise<AnalysisResult[]> {
    if (userId) dto.userId = userId;
    const normalizedData = await this.metaAdsService.fetchInsights(dto);
    return this.analyticsService.analyzeBatch(normalizedData);
  }

  @Post('tiktok')
  @UseGuards(SubscriptionGuard)
  @ApiHeader({ name: 'x-user-id', description: 'User ID for subscription check' })
  @ApiOperation({ summary: 'Fetch from TikTok then analyze | الجلب من تيك توك ثم التحليل' })
  @ApiResponse({ status: 200, type: [AnalysisResult] })
  async analyzeTikTok(@Body() dto: any): Promise<AnalysisResult[]> {
    const normalizedData = await this.tiktokAdsService.fetchInsights(dto);
    return this.analyticsService.analyzeBatch(normalizedData);
  }

  @Post('google')
  @UseGuards(SubscriptionGuard)
  @ApiHeader({ name: 'x-user-id', description: 'User ID for subscription check' })
  @ApiOperation({ summary: 'Fetch from Google then analyze | الجلب من جوجل ثم التحليل' })
  @ApiResponse({ status: 200, type: [AnalysisResult] })
  async analyzeGoogle(@Body() dto: any): Promise<AnalysisResult[]> {
    const normalizedData = await this.googleAdsService.fetchInsights(dto);
    return this.analyticsService.analyzeBatch(normalizedData);
  }

  @Post('sample')
  @ApiHeader({ name: 'x-user-id', description: 'User ID for tracking (No subscription required for sample)' })
  @ApiOperation({ summary: 'Analyze sample data (Dynamic or Fallback) | تحليل بيانات تجريبية (ديناميكي أو احتياطي)' })
  @ApiResponse({ status: 200, type: [AnalysisResult] })
  async analyzeSample(@Body() customData?: any[]): Promise<AnalysisResult[]> {
    // If user provides data in the body, use it. Otherwise, use demo data.
    // إذا قدم المستخدم بيانات، نستخدمها. وإلا، نستخدم البيانات التجريبية.
    const dataToAnalyze = (customData && customData.length > 0) ? customData : [
      {
        campaignId: '999001',
        campaignName: 'Winter Sale 2024 (Demo)',
        impressions: 15000,
        clicks: 120,
        spend: 45.5,
        ctr: 0.8,
        cpc: 0.38,
        cpm: 3.03,
        dateStart: '2024-01-01',
        dateStop: '2024-01-15',
        source: 'meta',
        imageUrl: '/api/assets/meta_ad_sample.png',
        reach: 12000,
        frequency: 1.25,
        objective: 'OUTCOME_SALES',
        status: 'ACTIVE',
        platform: 'facebook',
      },
      {
        campaignId: '999002',
        campaignName: 'Product Launch - Aggregated',
        impressions: 3000,
        clicks: 150,
        spend: 120.0,
        ctr: 5.0,
        cpc: 0.8,
        cpm: 40.0,
        dateStart: '2024-02-01',
        dateStop: '2024-02-05',
        source: 'meta',
        platform: 'facebook',
        status: 'ACTIVE',
      },
      {
        campaignId: '999002',
        campaignName: 'Product Launch - Aggregated',
        impressions: 2000,
        clicks: 100,
        spend: 80.0,
        ctr: 5.0,
        cpc: 0.8,
        cpm: 40.0,
        dateStart: '2024-02-01',
        dateStop: '2024-02-05',
        source: 'meta',
        platform: 'instagram',
        status: 'ACTIVE',
      },
      {
        campaignId: '999003',
        campaignName: 'Google Search Promo',
        impressions: 12000,
        clicks: 450,
        spend: 500.0,
        ctr: 3.75,
        cpc: 1.11,
        cpm: 41.67,
        dateStart: '2024-02-01',
        dateStop: '2024-02-10',
        source: 'google',
        status: 'ACTIVE',
        platform: 'google',
      },
      {
        campaignId: '999004',
        campaignName: 'TikTok Viral Dance',
        impressions: 150000,
        clicks: 3000,
        spend: 150.0,
        ctr: 2.0,
        cpc: 0.05,
        cpm: 1.0,
        dateStart: '2024-02-01',
        dateStop: '2024-02-10',
        source: 'tiktok',
        status: 'ACTIVE',
        platform: 'tiktok',
      },
    ];

    return this.analyticsService.analyzeBatch(dataToAnalyze);
  }

  @Post('visual')
  @ApiHeader({ name: 'x-user-id', description: 'User ID for tracking (No subscription required for visual)' })
  @ApiOperation({ summary: 'Analyze ad creative visually (AI Vision) | تحليل التصميم بصرياً' })
  async analyzeVisual(
    @Body() dto: AnalyzeVisualDto,
    @Headers('x-user-id') userId?: string,
  ): Promise<{ feedback: string }> {
    console.log('--- Analyze Visual DTO Received ---');
    console.log(JSON.stringify(dto, null, 2));

    let tier = 'standard';
    if (userId) {
      try {
        const user = await this.usersService.findById(userId);
        tier = user.subscriptionTier === 'pro' ? 'pro' : 'standard';
      } catch (e) {
        // Fallback to standard if user not found | العودة للمستوى العادي إذا لم يتم العثور على المستخدم
      }
    }

    const feedback = await this.analyticsService.analyzeVisual(
      dto.imageUrl,
      dto.adCopy,
      dto.metrics,
      tier,
      dto.campaignId
    );
    return { feedback };
  }
}
