<?php

namespace App\Services;

use App\Models\Ad;
use App\Models\AdAnalytics;
use Carbon\Carbon;

class AIInsightsService
{
    /**
     * Generate AI-powered suggestions for an ad
     */
    public function generateSuggestions(Ad $ad): array
    {
        $suggestions = [];
        
        // Get recent analytics (last 30 days)
        $analytics = AdAnalytics::forAd($ad->id)
            ->dateRange(Carbon::now()->subDays(30), Carbon::now())
            ->get();
        
        if ($analytics->isEmpty()) {
            return [[
                'type' => 'info',
                'icon' => 'info',
                'message' => 'Not enough data yet. Check back after a few days!',
                'priority' => 1,
            ]];
        }
        
        // Calculate aggregated metrics
        $totalImpressions = $analytics->sum('impressions');
        $totalViews = $analytics->sum('views');
        $totalClicks = $analytics->sum('clicks');
        $avgCtr = $analytics->avg('ctr');
        $avgBounceRate = $analytics->avg('bounce_rate');
        
        // 1. Low CTR Detection
        if ($avgCtr < 2 && $totalImpressions > 100) {
            $suggestions[] = [
                'type' => 'warning',
                'icon' => 'trending_down',
                'message' => 'Your CTR is below average. Consider improving your title and adding high-quality photos.',
                'action' => 'Optimize Ad',
                'priority' => 3,
            ];
        }
        
        // 2. High Bounce Rate
        if ($avgBounceRate > 50) {
            $suggestions[] = [
                'type' => 'warning',
                'icon' => 'exit_to_app',
                'message' => 'High bounce rate detected. Add more details and clearer pricing to keep visitors engaged.',
                'action' => 'Update Description',
                'priority' => 3,
            ];
        }
        
        // 3. Photo Count Analysis
        $photoCount = $ad->images()->count();
        if ($photoCount < 3) {
            $suggestions[] = [
                'type' => 'tip',
                'icon' => 'photo_camera',
                'message' => "Ads with 5+ photos get 30% more views. You have $photoCount photos. Add more!",
                'action' => 'Add Photos',
                'priority' => 2,
            ];
        }
        
        // 4. Pricing Intelligence
        $pricingSuggestion = $this->analyzePricing($ad);
        if ($pricingSuggestion) {
            $suggestions[] = $pricingSuggestion;
        }
        
        // 5. Temporal Pattern Detection
        $temporalSuggestion = $this->analyzeTemporalPatterns($analytics);
        if ($temporalSuggestion) {
            $suggestions[] = $temporalSuggestion;
        }
        
        // 6. Content Quality
        if (strlen($ad->description ?? '') < 100) {
            $suggestions[] = [
                'type' => 'tip',
                'icon' => 'description',
                'message' => 'Detailed descriptions build trust. Add more information about condition, features, and benefits.',
                'action' => 'Expand Description',
                'priority' => 2,
            ];
        }
        
        // 7. Good Performance Praise
        if ($avgCtr > 5 && $totalViews > 50) {
            $suggestions[] = [
                'type' => 'success',
                'icon' => 'celebration',
                'message' => '🎉 Great performance! Your ad is performing above average. Keep it up!',
                'priority' => 1,
            ];
        }
        
        // Sort by priority (higher first)
        usort($suggestions, fn($a, $b) => ($b['priority'] ?? 0) <=> ($a['priority'] ?? 0));
        
        return $suggestions;
    }
    
    /**
     * Analyze pricing compared to similar ads
     */
    private function analyzePricing(Ad $ad): ?array
    {
        if (!$ad->price) {
            return null;
        }
        
        // Find similar ads in the same category
        $similarAds = Ad::where('category_id', $ad->category_id)
            ->where('id', '!=', $ad->id)
            ->where('status', 'active')
            ->whereNotNull('price')
            ->limit(20)
            ->pluck('price')
            ->toArray();
        
        if (count($similarAds) < 5) {
            return null;
        }
        
        $avgPrice = array_sum($similarAds) / count($similarAds);
        $priceDiff = (($ad->price - $avgPrice) / $avgPrice) * 100;
        
        if ($priceDiff > 15) {
            return [
                'type' => 'warning',
                'icon' => 'attach_money',
                'message' => sprintf('Your price is %.0f%% higher than similar ads. Consider adjusting to $%.0f for better visibility.', $priceDiff, $avgPrice),
                'action' => 'Review Price',
                'priority' => 3,
            ];
        } elseif ($priceDiff < -20) {
            return [
                'type' => 'info',
                'icon' => 'trending_up',
                'message' => sprintf('Your price is lower than market. You could increase it to $%.0f.', $avgPrice),
                'priority' => 1,
            ];
        }
        
        return null;
    }
    
    /**
     * Analyze temporal patterns (weekends, time of day)
     */
    private function analyzeTemporalPatterns($analytics): ?array
    {
        if ($analytics->count() < 7) {
            return null;
        }
        
        $weekendViews = 0;
        $weekdayViews = 0;
        
        foreach ($analytics as $stat) {
            $dayOfWeek = $stat->date->dayOfWeek;
            if (in_array($dayOfWeek, [5, 6, 0])) { // Fri, Sat, Sun
                $weekendViews += $stat->views;
            } else {
                $weekdayViews += $stat->views;
            }
        }
        
        if ($weekendViews > $weekdayViews * 1.3) {
            return [
                'type' => 'tip',
                'icon' => 'schedule',
                'message' => 'Your ad gets 30%+ more views on weekends. Consider boosting Friday-Sunday for maximum impact.',
                'action' => 'Boost on Weekends',
                'priority' => 2,
            ];
        }
        
        return null;
    }
    
    /**
     * Get suggestions for all user's ads
     */
    public function getUserSuggestions(int $userId): array
    {
        $ads = Ad::where('user_id', $userId)
            ->where('status', 'active')
            ->limit(10)
            ->get();
        
        $allSuggestions = [];
        
        foreach ($ads as $ad) {
            $suggestions = $this->generateSuggestions($ad);
            foreach ($suggestions as $suggestion) {
                $suggestion['ad_id'] = $ad->id;
                $suggestion['ad_title'] = $ad->title;
                $allSuggestions[] = $suggestion;
            }
        }
        
        // Sort by priority and limit to top 10
        usort($allSuggestions, fn($a, $b) => ($b['priority'] ?? 0) <=> ($a['priority'] ?? 0));
        
        return array_slice($allSuggestions, 0, 10);
    }
}
