<?php

namespace App\Http\Controllers;

use Illuminate\Http\JsonResponse;
use App\Http\Requests\AiRespondRequest;
use App\Services\AI\LlmProvider;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use App\Services\Analytics\EventBus;

class AIController extends Controller
{
    use PersistsAiChat;
    public function respond(AiRespondRequest $request): JsonResponse
    {
        $payload = $request->validated();
        /** @var LlmProvider $provider */
        $provider = app(LlmProvider::class);
        $attempts = 0;
        $maxAttempts = 2; // one retry on invalid JSON
        $last = null;
        do {
            $attempts++;
            $last = $provider->respond($payload);
            if (isset($payload['response_format']['type']) && $payload['response_format']['type'] === 'json_object') {
                if ($this->isValidValuationJson($last['json'] ?? null)) {
                    $this->persistChatAndTrack($request, $last);
                    return response()->json($last);
                }
                Log::warning('Invalid valuation JSON from provider', ['attempt' => $attempts]);
            } else {
                $this->persistChatAndTrack($request, $last);
                return response()->json($last);
            }
        } while ($attempts < $maxAttempts);
        // Fallback to text
        $fallback = [
            'text' => 'نتوانستم خروجی ساختاری تولید کنم؛ لطفاً جزئیات بیشتری بدهید.',
            'response_id' => $last['response_id'] ?? null,
            'token_in' => $last['token_in'] ?? 0,
            'token_out' => $last['token_out'] ?? 0,
            'latency_ms' => $last['latency_ms'] ?? 0,
        ];
        $this->persistChatAndTrack($request, $fallback);
        return response()->json($fallback);
    }

    private function isValidValuationJson($json): bool
    {
        if (!is_array($json)) return false;
        foreach (['min','max','anchor','confidence','reasons'] as $k) {
            if (!array_key_exists($k, $json)) return false;
        }
        if (!in_array($json['confidence'], ['low','medium','high'])) return false;
        if (!is_array($json['reasons'])) return false;
        return true;
    }
}

trait PersistsAiChat
{
    private function persistChatAndTrack(Request $request, array $result): void
    {
        try {
            $uid = optional($request->user())->id;
            if ($uid) {
                DB::table('chats')->insert([
                    'user_id'     => $uid,
                    'module'      => 'valuation',
                    'role'        => 'assistant',
                    'text'        => $result['text'] ?? null,
                    'response_id' => $result['response_id'] ?? null,
                    'token_in'    => (int)($result['token_in'] ?? 0),
                    'token_out'   => (int)($result['token_out'] ?? 0),
                    'latency_ms'  => (int)($result['latency_ms'] ?? 0),
                    'created_at'  => now(),
                    'updated_at'  => now(),
                ]);

                if (isset($result['json'])) {
                    EventBus::track($uid, 'PriceCheck', [
                        'latency_ms' => (int)($result['latency_ms'] ?? 0),
                        'confidence' => $result['json']['confidence'] ?? null,
                        'anchor'     => $result['json']['anchor'] ?? null,
                    ]);
                }
            }
        } catch (\Throwable $e) {
            // no-op
        }
    }
}
