<?php

namespace App\Services;

use App\Models\Ad;
use App\Models\User;
use App\Models\Setting;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;

class AiGuardianService
{
    protected $mode;
    protected $sensitivity; // low, medium, high
    protected $autoBanEnabled;
    protected $reportThreshold;

    protected $trustThresholds = [];

    public function __construct()
    {
        $this->mode = Setting::where('key', 'guardian_mode')->value('value') ?? 'BALANCED';
        $this->autoBanEnabled = Setting::where('key', 'guardian_auto_ban')->value('value') == '1';
        $this->reportThreshold = (int)(Setting::where('key', 'guardian_report_threshold')->value('value') ?? 3);
        
        // Load Dynamic Trust Thresholds
        $this->trustThresholds = [
            'STRICT' => (int)(Setting::where('key', 'guardian_strict_threshold')->value('value') ?? 80),
            'BALANCED' => (int)(Setting::where('key', 'guardian_balanced_threshold')->value('value') ?? 50),
            'RELAXED' => (int)(Setting::where('key', 'guardian_relaxed_threshold')->value('value') ?? 20),
        ];

        // Define sensitivity based on mode
        switch ($this->mode) {
            case 'STRICT':
                $this->sensitivity = 'high';
                break;
            case 'RELAXED':
                $this->sensitivity = 'low';
                break;
            default:
                $this->sensitivity = 'medium';
        }
    }

    /**
     * Analyze an ad for risk before posting
     */
    public function analyzeAd($title, $description, User $user)
    {
        $issues = [];
        $suggestions = [];
        $riskLevel = 'LOW';
        $action = 'APPROVE';

        // 1. Check Trust Score
        $trustScore = optional($user->trustScore)->score ?? 50; // Default 50 for new users
        $trustThreshold = $this->getTrustThreshold();

        if ($trustScore < $trustThreshold) {
            $riskLevel = 'MEDIUM'; // Not automatically high, but warrants scrutiny
            // In STRICT mode, low trust might force pending
            if ($this->mode === 'STRICT') {
                $action = 'FLAG_FOR_REVIEW'; 
                $issues[] = "User trust score ($trustScore) is below threshold ($trustThreshold).";
            }
        }

        // 2. Content Analysis (Keywords & Patterns)
        $text = $title . ' ' . $description;
        $contentAnalysis = $this->analyzeContent($text);

        if (!empty($contentAnalysis['issues'])) {
            $issues = array_merge($issues, $contentAnalysis['issues']);
            $suggestions = array_merge($suggestions, $contentAnalysis['suggestions']);
            
            // Upgrade risk level based on content severity
            if ($contentAnalysis['severity'] === 'HIGH') {
                $riskLevel = 'HIGH';
                $action = 'AUTO_BAN'; // Or severe reject
            } elseif ($contentAnalysis['severity'] === 'MEDIUM') {
                $riskLevel = ($riskLevel === 'LOW') ? 'MEDIUM' : 'HIGH';
                $action = 'SUGGEST_CHANGES'; // Feedback loop
            }
        }

        // 3. Spam Detection (Caps, Repetition)
        if ($this->detectSpam($text)) {
            $riskLevel = 'MEDIUM';
            $action = ($action === 'APPROVE') ? 'SUGGEST_CHANGES' : $action;
            $suggestions[] = "Please reduce the use of capital letters and repeated punctuation.";
        }

        // Final Decision Logic
        if ($action === 'AUTO_BAN' && !$this->autoBanEnabled) {
            $action = 'FLAG_FOR_REVIEW'; // Fallback if auto-ban disabled
        }

        // Log significant actions (exclude generic approvals)
        if (in_array($action, ['AUTO_BAN', 'FLAG_FOR_REVIEW', 'SUGGEST_CHANGES'])) {
            $this->logAction($action, 'Ad Submission', $user->id, 'User', array_merge($issues, $suggestions), [
                'title' => $title,
                'description' => $description
            ]);
        }

        return [
            'risk_level' => $riskLevel,
            'action' => $action,
            'suggestions' => $suggestions,
            'reasons' => $issues
        ];
    }

    /**
     * Re-evaluate an existing ad (e.g., after reports)
     */
    public function evaluateAdHealth(Ad $ad)
    {
        $reports = $ad->reports()->count();
        $reportsWeight = $reports * 10; // Each report adds 10 risk points
        
        // Simple heuristic: If reports exceed threshold, suspend
        if ($reports >= $this->reportThreshold) {
            $reason = "Ad received $reports reports, exceeding the safe limit of {$this->reportThreshold}.";
            
            $this->logAction('SUSPEND', 'Report Reactor', $ad->id, 'Ad', [$reason], ['reports' => $reports]);

            return [
                'action' => 'SUSPEND',
                'reason' => $reason
            ];
        }

        return ['action' => 'KEEP_ACTIVE'];
    }

    /**
     * Check chat message for scams
     */
    public function scanMessage($content)
    {
        $scamTriggers = [
            'western union', 'moneygram', 'cash app', 'venmo', 'wire transfer', 
            'shipping fee', 'courier agent', 'verify code', 'google voice', 
            'pay me first', 'deposit'
        ];

        foreach ($scamTriggers as $trigger) {
            if (Str::contains(Str::lower($content), $trigger)) {
                
                // We don't have user ID here easily unless passed, but caller handles punishment.
                // We should make scanMessage accept user/sender ID if we want to log here.
                // For now, caller of scanMessage (listener) should log or we rely on listener. 
                // Let's refactor listener to call log, OR make this method pure.
                // Decision: Make method return result and let Listener interact with Guardian logger if possible, 
                // BUT better encapsulation is if we log it here if we had context.
                // Since this is a utility method, let's keep it pure for now, but Listener will trigger the log.
                
                return [
                    'detected' => true,
                    'trigger' => $trigger,
                    'severity' => 'HIGH'
                ];
            }
        }

        return ['detected' => false];
    }

    // --- Internal Helpers ---

    protected function analyzeContent($text)
    {
        $text = Str::lower($text);
        $issues = [];
        $suggestions = [];
        $severity = 'LOW';

        // High Risk Keywords (Banned)
        $bannedWords = ['scam', 'fraud', 'drugs', 'weapon', 'gun', 'casino', 'xxx', 'porn'];
        foreach ($bannedWords as $word) {
            if (Str::contains($text, $word)) {
                $issues[] = "Contains prohibited word: '$word'";
                $suggestions[] = "Remove prohibited content related to '$word'.";
                $severity = 'HIGH';
            }
        }

        // Medium Risk (Profanity / Suspicious)
        $suspiciousWords = ['damn', 'hell', 'stupid', 'idiot', 'hack', 'crack'];
        foreach ($suspiciousWords as $word) {
            if (Str::contains($text, $word)) {
                $issues[] = "Contains unprofessional language: '$word'";
                $suggestions[] = "Please use professional language and remove '$word'.";
                if ($severity !== 'HIGH') $severity = 'MEDIUM';
            }
        }

        return ['issues' => $issues, 'suggestions' => $suggestions, 'severity' => $severity];
    }

    protected function detectSpam($text)
    {
        // Check for excessive caps (simple ratio)
        $capsCount = preg_match_all('/[A-Z]/', $text);
        $totalCount = strlen($text);
        
        if ($totalCount > 10 && ($capsCount / $totalCount) > 0.6) {
            return true;
        }

        // Check for repated punctuation !!! ???
        if (preg_match('/[!?.]{4,}/', $text)) {
            return true;
        }

        return false;
    }

    protected function getTrustThreshold()
    {
        return $this->trustThresholds[$this->mode] ?? 50;
    }

    /**
     * Log an action to the GuardianLogs table
     */
    public function logAction($action, $reasonType, $targetId, $targetType, $details = [], $snapshot = [])
    {
        try {
            \App\Models\GuardianLog::create([
                'action' => $action,
                'target_type' => $targetType,
                'target_id' => $targetId,
                'reason' => "$reasonType: " . implode(', ', $details),
                'snapshot' => $snapshot
            ]);
        } catch (\Exception $e) {
            Log::error("Failed to create Guardian Log: " . $e->getMessage());
        }
    }
}
