<?php

namespace App\Http\Controllers;

use App\Models\SystemAssistantLog;
use App\Services\SystemAssistantService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class SystemAssistantController extends Controller
{
    public function __construct()
    {
        $this->middleware('permission:system_assistant.chat.view')->only(['index', 'ask', 'message']);
        $this->middleware('permission:system_assistant.notes_reminders.view')->only(['notesReminders']);
    }

    public function notesReminders()
    {
        return view('system_assistant.notes_reminders', [
            'user' => Auth::user(),
        ]);
    }

    public function index()
    {
        return view('system_assistant.index');
    }

    public function message(Request $request, SystemAssistantService $assistant)
    {
        $data = $request->validate([
            'message' => 'required|string|max:2000',
            'session_id' => 'nullable|string|max:255',
            'history' => 'nullable|array', // Optional, but useful for short-term memory
        ]);

        $user = $request->user();
        $message = trim($data['message']);
        $sessionId = $data['session_id'] ?? (string) Str::uuid();
        $history = $data['history'] ?? [];

        // Retrieve session context from cache
        $cacheKey = 'sa_context_'.$sessionId;
        $sessionContext = Cache::get($cacheKey, []);

        $startedAt = microtime(true);
        $status = 'success';
        $tool = null;
        $intent = null;
        $params = null;
        $summary = null;
        $requestType = 'unknown';
        $result = [];

        try {
            // Process the message
            $result = $assistant->answer($message, $user, $history, $sessionContext);

            $tool = $result['tool'] ?? 'unknown';
            $intent = $result['intent'] ?? 'unknown';
            $params = $result['params'] ?? null;
            $summary = $result['summary'] ?? '';
            $requestType = $result['request_type'] ?? 'unknown';

            // Update session context
            if (! empty($result['context'])) {
                $sessionContext = array_merge($sessionContext, $result['context']);
                Cache::put($cacheKey, $sessionContext, now()->addMinutes(60)); // 1 hour expiration
            }
        } catch (\Throwable $e) {
            $status = 'error';
            $summary = $e->getMessage();
            Log::error('SystemAssistant Error: '.$e->getMessage(), [
                'trace' => $e->getTraceAsString(),
                'user_id' => $user->id,
                'message' => $message,
            ]);

            // Return user-friendly error response
            $result = [
                'request_type' => 'error',
                'text' => __('system_assistant.error_generic'),
                'choices' => [],
                'data' => null,
            ];
        }

        $executionMs = (int) round((microtime(true) - $startedAt) * 1000);

        // Log the interaction
        $logRow = SystemAssistantLog::create([
            'user_id' => $user->id,
            'session_id' => $sessionId,
            'question' => $message,
            'request_type' => $requestType,
            'tool' => $tool,
            'intent' => $intent,
            'params_json' => $params,
            'result_summary' => $summary,
            'execution_time_ms' => $executionMs,
            'status' => $status,
            'created_at' => now(),
        ]);

        Log::info('system_assistant_message', [
            'log_id' => $logRow->id,
            'user_id' => $user->id,
            'session_id' => $sessionId,
            'intent' => $intent,
            'status' => $status,
            'execution_time_ms' => $executionMs,
        ]);

        return response()->json([
            'session_id' => $sessionId,
            'request_type' => $result['request_type'] ?? null,
            'text' => $result['text'] ?? '',
            'choices' => $result['choices'] ?? [],
            'data' => $result['data'] ?? null,
            'execution_time_ms' => $executionMs,
            'context' => $sessionContext, // Return updated context for debugging/client-side use if needed
        ]);
    }

    public function ask(Request $request, SystemAssistantService $assistant)
    {
        $data = $request->validate([
            'question' => 'required|string|max:2000',
            'history' => 'nullable|array',
        ]);

        $user = $request->user();
        $question = trim($data['question']);
        $history = $data['history'] ?? [];

        $startedAt = microtime(true);
        $result = $assistant->answer($question, $user, $history);
        $executionMs = (int) round((microtime(true) - $startedAt) * 1000);

        $logRow = SystemAssistantLog::create([
            'user_id' => $user->id,
            'question' => $question,
            'request_type' => (string) ($result['request_type'] ?? ''),
            'params_json' => $result['params'] ?? null,
            'result_summary' => (string) ($result['summary'] ?? ''),
            'execution_time_ms' => $executionMs,
            'created_at' => now(),
        ]);

        Log::info('system_assistant', [
            'log_id' => $logRow->id,
            'user_id' => $user->id,
            'request_type' => $result['request_type'] ?? null,
            'execution_time_ms' => $executionMs,
        ]);

        return response()->json([
            'request_type' => $result['request_type'] ?? null,
            'text' => $result['text'] ?? '',
            'choices' => $result['choices'] ?? [],
            'data' => $result['data'] ?? null,
            'execution_time_ms' => $executionMs,
        ]);
    }
}
