<?php

namespace App\Services;

use App\Models\AdCampaign;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class MarketingIntelligenceService
{
    protected $baseUrl;

    protected $model;

    public function __construct()
    {
        $this->baseUrl = rtrim((string) env('OLLAMA_URL', 'http://127.0.0.1:11434'), '/');
        $this->model = (string) env('OLLAMA_MODEL', 'mistral:7b-instruct');
    }

    /**
     * Suggest interests based on business info using LLM.
     */
    public function suggestInterests(string $businessType, string $location): array
    {
        if (empty($this->baseUrl)) {
            return $this->getFallbackInterests($businessType);
        }

        $prompt = "Act as a Facebook Ads Expert. Suggest 10 highly relevant Facebook Ad interests for a '{$businessType}' business located in '{$location}'. Return ONLY a JSON array of strings. Example: [\"Interest 1\", \"Interest 2\"]. Do not add any text outside the JSON.";

        try {
            $response = Http::timeout(30)->post($this->baseUrl.'/api/chat', [
                'model' => $this->model,
                'stream' => false,
                'messages' => [
                    ['role' => 'user', 'content' => $prompt],
                ],
                'options' => ['temperature' => 0.7],
            ]);

            if ($response->successful()) {
                $content = $response->json('message.content');
                // Clean up markdown code blocks if present
                $content = preg_replace('/```json|```/', '', $content);
                $interests = json_decode(trim($content), true);

                if (is_array($interests)) {
                    return array_slice($interests, 0, 10);
                }
            }
        } catch (\Exception $e) {
            Log::error('Ollama Audience Suggestion Error: '.$e->getMessage());
        }

        return $this->getFallbackInterests($businessType);
    }

    /**
     * Suggest 3 ad copies using LLM.
     */
    public function suggestAdCopies(string $businessName, string $businessType, string $objective, string $language = 'ar'): array
    {
        if (empty($this->baseUrl)) {
            return $this->getFallbackAdCopies();
        }

        $langInstruction = $language === 'ar' ? 'in Arabic' : 'in English';

        $prompt = "Act as a Professional Copywriter. Write 3 distinct Facebook Ad copies for a '{$businessType}' named '{$businessName}' with objective '{$objective}'. Write {$langInstruction}. 
        Return ONLY a JSON array of objects, where each object has: 'headline', 'primary_text', 'description', 'call_to_action'.
        Format: [{\"headline\": \"...\", \"primary_text\": \"...\", \"description\": \"...\", \"call_to_action\": \"...\"}, ...]";

        try {
            $response = Http::timeout(45)->post($this->baseUrl.'/api/chat', [
                'model' => $this->model,
                'stream' => false,
                'messages' => [
                    ['role' => 'user', 'content' => $prompt],
                ],
                'options' => ['temperature' => 0.8],
            ]);

            if ($response->successful()) {
                $content = $response->json('message.content');
                $content = preg_replace('/```json|```/', '', $content);
                $copies = json_decode(trim($content), true);

                if (is_array($copies)) {
                    return array_slice($copies, 0, 3);
                }
            }
        } catch (\Exception $e) {
            Log::error('Ollama Ad Copy Suggestion Error: '.$e->getMessage());
        }

        return $this->getFallbackAdCopies();
    }

    /**
     * Rule-based Performance Analysis.
     */
    public function analyzePerformance(AdCampaign $campaign): array
    {
        // Aggregate reports
        $reports = $campaign->reports;

        if ($reports->isEmpty()) {
            return ['status' => 'no_data', 'message' => __('reports.no_data_yet')];
        }

        $totalSpend = $reports->sum('spend');
        $impressions = $reports->sum('impressions');
        $clicks = $reports->sum('clicks');
        $results = $reports->sum('results');

        $ctr = $impressions > 0 ? ($clicks / $impressions) * 100 : 0;
        $cpc = $clicks > 0 ? $totalSpend / $clicks : 0;
        $cpr = $results > 0 ? $totalSpend / $results : 0;

        $insights = [];

        // CTR Analysis
        if ($ctr < 1.0) {
            $insights[] = [
                'type' => 'bad',
                'metric' => 'CTR',
                'value' => number_format($ctr, 2).'%',
                'observation' => __('marketing.insight_low_ctr'),
                'recommendation' => __('marketing.rec_improve_creative'),
            ];
        } elseif ($ctr > 2.0) {
            $insights[] = [
                'type' => 'good',
                'metric' => 'CTR',
                'value' => number_format($ctr, 2).'%',
                'observation' => __('marketing.insight_good_ctr'),
                'recommendation' => __('marketing.rec_scale_budget'),
            ];
        }

        // CPR Analysis (Simple threshold, ideally should be benchmarked)
        if ($cpr > 20) { // Arbitrary high cost
            $insights[] = [
                'type' => 'bad',
                'metric' => 'Cost Per Result',
                'value' => number_format($cpr, 2),
                'observation' => __('marketing.insight_high_cpr'),
                'recommendation' => __('marketing.rec_refine_audience'),
            ];
        }

        return [
            'status' => 'analyzed',
            'ctr' => $ctr,
            'cpc' => $cpc,
            'cpr' => $cpr,
            'insights' => $insights,
        ];
    }

    /**
     * Budget Optimization Suggestions.
     */
    public function optimizeBudget(AdCampaign $campaign): array
    {
        $analysis = $this->analyzePerformance($campaign);
        $recommendations = [];

        if ($analysis['status'] === 'analyzed') {
            if ($analysis['ctr'] > 2.0 && $analysis['cpr'] < 10) {
                $recommendations[] = [
                    'campaign_name' => $campaign->campaign_name,
                    'action' => 'increase_budget',
                    'reason' => __('marketing.high_performance_reason'),
                    'suggestion' => __('marketing.increase_budget_suggestion'),
                ];
            } elseif ($analysis['ctr'] < 0.5) {
                $recommendations[] = [
                    'campaign_name' => $campaign->campaign_name,
                    'action' => 'decrease_budget',
                    'reason' => __('marketing.low_performance_reason'),
                    'suggestion' => __('marketing.decrease_budget_suggestion'),
                ];
            }
        }

        return $recommendations;
    }

    /**
     * Generate a simplified client report with text summary.
     */
    public function generateClientReport(AdCampaign $campaign, string $language = 'ar'): array
    {
        $analysis = $this->analyzePerformance($campaign);

        if ($analysis['status'] === 'no_data') {
            return $analysis;
        }

        $reports = $campaign->reports;
        $impressions = $reports->sum('impressions');
        $clicks = $reports->sum('clicks');
        $spend = $reports->sum('spend');
        $results = $reports->sum('results');
        $cpr = $results > 0 ? $spend / $results : 0;

        // Prepare data for summary
        $data = [
            'impressions' => number_format($impressions),
            'clicks' => number_format($clicks),
            'spend' => number_format($spend, 2),
            'cpr' => number_format($cpr, 2),
            'currency' => '$', // Default currency
        ];

        $summary = $this->generateReportSummary($data, $language);

        return [
            'status' => 'success',
            'metrics' => [
                'impressions' => $impressions,
                'clicks' => $clicks,
                'spend' => $spend,
                'results' => $results,
                'cpr' => $cpr,
            ],
            'summary' => $summary,
        ];
    }

    private function generateReportSummary(array $data, string $language): string
    {
        if (! empty($this->baseUrl)) {
            // Use LLM
            $langInstruction = $language === 'ar' ? 'in Arabic' : 'in English';
            $prompt = "Act as a Marketing Consultant. Write a short, simple summary for a client report based on this data: 
            Impressions: {$data['impressions']}, Clicks: {$data['clicks']}, Spend: {$data['currency']}{$data['spend']}, Cost Per Result: {$data['currency']}{$data['cpr']}. 
            Write {$langInstruction}. Keep it under 50 words. Focus on the value delivered.";

            try {
                $response = Http::timeout(30)->post($this->baseUrl.'/api/chat', [
                    'model' => $this->model,
                    'stream' => false,
                    'messages' => [['role' => 'user', 'content' => $prompt]],
                    'options' => ['temperature' => 0.7],
                ]);

                if ($response->successful()) {
                    return trim($response->json('message.content'));
                }
            } catch (\Exception $e) {
                Log::error('Ollama Report Summary Error: '.$e->getMessage());
            }
        }

        // Fallback Template
        if ($language === 'ar') {
            return "هذه الحملة وصلت إلى {$data['impressions']} شخص، وحققت {$data['clicks']} نقرة، بإجمالي صرف {$data['currency']}{$data['spend']}، وتكلفة {$data['currency']}{$data['cpr']} لكل نتيجة.";
        }

        return "This campaign reached {$data['impressions']} people, generated {$data['clicks']} clicks, with a total spend of {$data['currency']}{$data['spend']}, and a cost of {$data['currency']}{$data['cpr']} per result.";
    }

    private function getFallbackInterests(string $type): array
    {
        $defaults = [
            'restaurant' => ['Food', 'Dining', 'Restaurants', 'Fast food', 'Pizza', 'Burger'],
            'real_estate' => ['Real Estate', 'Property', 'Apartments', 'House Hunting', 'Luxury Homes'],
            'retail' => ['Shopping', 'Fashion', 'Clothing', 'Sales', 'Online Shopping'],
            'default' => ['Small Business', 'Entrepreneurship', 'Marketing'],
        ];

        foreach ($defaults as $key => $values) {
            if (str_contains(strtolower($type), $key)) {
                return $values;
            }
        }

        return $defaults['default'];
    }

    private function getFallbackAdCopies(): array
    {
        return [
            [
                'headline' => 'Special Offer!',
                'primary_text' => 'Check out our amazing products. Limited time offer.',
                'description' => 'Shop now and save big.',
                'call_to_action' => 'SHOP_NOW',
            ],
            [
                'headline' => 'Don\'t Miss Out',
                'primary_text' => 'The best solution for your needs. Join thousands of happy customers.',
                'description' => 'Quality you can trust.',
                'call_to_action' => 'LEARN_MORE',
            ],
            [
                'headline' => 'New Arrival',
                'primary_text' => 'Discover the latest trends. Upgrade your lifestyle today.',
                'description' => 'Premium quality.',
                'call_to_action' => 'SHOP_NOW',
            ],
        ];
    }
}
