<?php

namespace App\Http\Controllers;

use App\Http\Requests\AiSalesAnalyzeRequest;
use App\Services\AiSalesService;
use App\Services\MarketInsightService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Log;

class AiSalesController extends Controller
{
    public function index(MarketInsightService $marketInsightService)
    {
        $settings = [];

        if (class_exists(\App\Models\Setting::class)) {
            try {
                $settings = \App\Models\Setting::pluck('value', 'key')->toArray();
            } catch (\Throwable $e) {
                $settings = [];
            }
        }

        $marketInsights = $marketInsightService->getInsights();

        return view('pages.ai.sales', [
            'settings' => $settings,
            'marketInsights' => $marketInsights,
        ]);
    }

    public function analyze(AiSalesAnalyzeRequest $request): JsonResponse
    {
        try {
            $service = new AiSalesService();

            $result = $service->generateSql($request->validated('question'));
            $rows = $service->execute($result['sql']);

            return response()->json([
                'ok' => true,
                'description' => $this->normalizeDescription((string) ($result['description'] ?? '')),
                'data' => $rows,
                'meta' => [
                    'rows' => count($rows),
                    'cols' => !empty($rows) && is_array($rows[0]) ? count($rows[0]) : 0,
                    'read_only' => true,
                    'source' => 'database-live',
                ],
            ]);
        } catch (\RuntimeException $e) {
            return response()->json([
                'ok' => false,
                'message' => $this->normalizeDescription($e->getMessage()),
                'hint' => $this->guessHint($e->getMessage()),
            ], 422);
        } catch (\Throwable $e) {
            Log::error('AI Sales analyze failed', [
                'message' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            return response()->json([
                'ok' => false,
                'message' => app()->hasDebugModeEnabled()
                    ? $this->normalizeDescription($e->getMessage())
                    : 'Terjadi gangguan pada fitur AI.',
                'hint' => 'Cek API key, base URL LiteLLM, koneksi internet, dan struktur database.',
            ], 500);
        }
    }

    private function normalizeDescription(string $text): string
    {
        $text = trim($text);

        if ($text === '') {
            return '';
        }

        $text = str_replace('_', ' ', $text);
        $text = preg_replace('/\s+/', ' ', $text);

        return trim($text);
    }

    private function guessHint(string $message): string
    {
        $msg = strtolower($message);

        if (str_contains($msg, 'litellm_api_key')) {
            return 'Isi LITELLM_API_KEY di .env atau services.php.';
        }

        if (str_contains($msg, 'litellm_base_url')) {
            return 'Isi LITELLM_BASE_URL di .env atau services.php.';
        }

        if (str_contains($msg, 'timeout')) {
            return 'Periksa koneksi ke LiteLLM, domain tujuan, dan API key.';
        }

        if (str_contains($msg, 'sql ditolak')) {
            return 'AI hanya boleh membuat query baca data. Coba pertanyaan yang lebih jelas.';
        }

        if (str_contains($msg, 'llm error')) {
            return 'Periksa endpoint LiteLLM, model, dan kredit API.';
        }

        return 'Periksa konfigurasi AI, internet server.';
    }
}
