<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Lead;
use App\Models\SupportTicket;
use App\Models\User;
use App\Models\Withdrawal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

/**
 * Admin-only AI assistant. Proxies chat to an OpenAI-compatible provider
 * (OpenRouter or NVIDIA). The API key is read server-side from site settings
 * and never leaves the server; the browser only ever sees the reply text.
 */
class AiAssistantController extends Controller
{
    private const ENDPOINTS = [
        'openrouter' => 'https://openrouter.ai/api/v1/chat/completions',
        'nvidia' => 'https://integrate.api.nvidia.com/v1/chat/completions',
    ];

    public function chat(Request $request)
    {
        if (!site_bool('ai_assistant_enabled', false)) {
            return response()->json(['error' => 'The AI assistant is disabled. Enable it in Settings.'], 403);
        }

        $data = $request->validate([
            'messages' => ['required', 'array', 'min:1', 'max:40'],
            'messages.*.role' => ['required', 'in:user,assistant'],
            'messages.*.content' => ['required', 'string', 'max:6000'],
            'model' => ['nullable', 'string', 'max:120'],
        ]);

        $provider = site_setting('ai_provider', 'openrouter');
        $endpoint = self::ENDPOINTS[$provider] ?? self::ENDPOINTS['openrouter'];
        $apiKey = trim((string) site_setting('ai_api_key', ''));
        $model = trim((string) ($data['model'] ?? '')) ?: trim((string) site_setting('ai_model', ''));

        if ($apiKey === '') {
            return response()->json(['error' => 'No AI API key is configured. Add one in Settings → AI Assistant.'], 422);
        }

        if ($model === '') {
            return response()->json(['error' => 'No AI model is selected. Choose one in Settings → AI Assistant.'], 422);
        }

        $messages = array_merge(
            [['role' => 'system', 'content' => $this->systemPrompt()]],
            array_map(fn ($m) => ['role' => $m['role'], 'content' => $m['content']], $data['messages'])
        );

        try {
            $response = Http::withToken($apiKey)
                ->timeout(45)
                ->withHeaders($provider === 'openrouter' ? [
                    'HTTP-Referer' => config('app.url'),
                    'X-Title' => brand_name().' Admin',
                ] : [])
                ->post($endpoint, [
                    'model' => $model,
                    'messages' => $messages,
                    'temperature' => 0.4,
                    'max_tokens' => 1000,
                ]);
        } catch (\Throwable $exception) {
            return response()->json(['error' => 'Could not reach the AI provider. Check the server can make outbound requests.'], 502);
        }

        if (!$response->successful()) {
            $providerError = $response->json('error.message') ?? $response->json('detail') ?? 'The AI provider returned an error.';

            return response()->json(['error' => is_string($providerError) ? $providerError : 'The AI provider returned an error.'], 502);
        }

        $reply = $response->json('choices.0.message.content');

        if (!is_string($reply) || $reply === '') {
            return response()->json(['error' => 'The AI provider returned an empty response.'], 502);
        }

        return response()->json(['reply' => trim($reply)]);
    }

    /**
     * Read-only, aggregate-only site context. No personal data is included so
     * the assistant can reason about the business without leaking PII.
     */
    private function systemPrompt(): string
    {
        $context = [
            'total_users' => User::count(),
            'new_users_today' => User::whereDate('created_at', today())->count(),
            'active_users_24h' => User::where('last_seen_at', '>=', now()->subDay())->count(),
            'banned_users' => User::where('is_banned', true)->count(),
            'pending_cashouts' => Withdrawal::where('status', 'pending')->count(),
            'approved_cashouts' => Withdrawal::where('status', 'approved')->count(),
            'revenue_total' => round((float) Lead::sum('payout'), 2),
            'revenue_today' => round((float) Lead::whereDate('created_at', today())->sum('payout'), 2),
            'leads_today' => Lead::whereDate('created_at', today())->count(),
            'open_tickets' => SupportTicket::whereIn('status', ['open', 'pending'])->count(),
        ];

        return 'You are the admin assistant for '.brand_name().', a GPT-style rewards/offerwall platform. '
            .'Help the admin understand and operate the site: analytics, fraud/anti-cheat, cashouts, offers, providers, and growth. '
            .'Be concise and practical. When asked for numbers, use this live snapshot (aggregate only, no personal data): '
            .json_encode($context)
            .'. If asked to do something you cannot do from chat (like changing settings or paying users), explain where in the admin panel to do it.';
    }
}
