<?php

namespace App\Services;

use App\Models\Complaint;
use Illuminate\Support\Str;

class ComplaintClassificationService
{
    /**
     * Emergency keywords
     */
    private array $emergencyKeywords = [
        'polisi' => ['polisi', 'polisi', 'kejahatan', 'pencurian', 'pembunuhan', 'perampokan', 'kekerasan', 'pemerkosaan'],
        'medis' => ['ambulans', 'sakit', 'kecelakaan', 'darurat medis', 'stroke', 'serangan jantung', 'pingsan', 'luka'],
        'kebakaran' => ['kebakaran', 'api', 'kobaran', 'terbakar', 'asap', 'damkar'],
        'bencana' => ['banjir', 'gempa', 'tsunami', 'longsor', 'angin topan', 'bencana alam'],
    ];

    /**
     * Non-emergency keywords
     */
    private array $nonEmergencyKeywords = [
        'pemda' => ['jalan rusak', 'lampu mati', 'sampah', 'drainase', 'infrastruktur'],
        'dinsos' => ['tunawisma', 'pengemis', 'anak jalanan', 'bantuan sosial'],
        'dishub' => ['macet', 'lalu lintas', 'parkir', 'rambu', 'lampu merah'],
    ];

    /**
     * Classify complaint
     */
    public function classify(string $description, ?string $callerPhone = null): array
    {
        $description = Str::lower($description);
        $keywords = [];
        $category = 'emergency_police';
        $priority = 'medium';

        // Check emergency keywords
        foreach ($this->emergencyKeywords as $type => $words) {
            foreach ($words as $word) {
                if (Str::contains($description, $word)) {
                    $keywords[] = $word;
                    
                    switch ($type) {
                        case 'polisi':
                            $category = 'emergency_police';
                            $priority = 'high';
                            break;
                        case 'medis':
                            $category = 'emergency_medical';
                            $priority = 'critical';
                            break;
                        case 'kebakaran':
                            $category = 'emergency_fire';
                            $priority = 'critical';
                            break;
                        case 'bencana':
                            $category = 'emergency_disaster';
                            $priority = 'critical';
                            break;
                    }
                    break 2;
                }
            }
        }

        // Check non-emergency keywords
        if ($category === 'emergency_police' && empty($keywords)) {
            foreach ($this->nonEmergencyKeywords as $type => $words) {
                foreach ($words as $word) {
                    if (Str::contains($description, $word)) {
                        $keywords[] = $word;
                        $category = 'non_emergency';
                        $priority = 'low';
                        break 2;
                    }
                }
            }
        }

        // AI classification (placeholder for actual AI integration)
        $aiClassification = $this->aiClassify($description);

        return [
            'category' => $category,
            'priority' => $priority,
            'keywords' => array_unique($keywords),
            'ai_classification' => $aiClassification,
        ];
    }

    /**
     * AI classification (placeholder for actual AI/ML integration)
     */
    private function aiClassify(string $description): string
    {
        // This would integrate with actual AI/ML service
        // For now, return basic classification
        return json_encode([
            'confidence' => 0.85,
            'suggested_category' => 'emergency_police',
            'entities' => [],
        ]);
    }

    /**
     * Get recommended disposition based on category
     */
    public function getRecommendedDisposition(string $category): array
    {
        return match($category) {
            'emergency_police' => [
                'unit_type' => 'samapta',
                'external_agencies' => [],
            ],
            'emergency_medical' => [
                'unit_type' => 'medis',
                'external_agencies' => ['rs'],
            ],
            'emergency_fire' => [
                'unit_type' => 'damkar',
                'external_agencies' => ['damkar'],
            ],
            'emergency_disaster' => [
                'unit_type' => 'sar',
                'external_agencies' => ['bpbd', 'bnpb', 'basarnas'],
            ],
            'non_emergency' => [
                'unit_type' => null,
                'external_agencies' => ['pemda', 'dinsos', 'dishub'],
            ],
            default => [
                'unit_type' => 'samapta',
                'external_agencies' => [],
            ],
        };
    }
}
