<?php

namespace App\Http\Controllers;

use App\Models\HomepageLead;
use App\Models\SystemSetting;
use App\Services\HomepageAgentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

/**
 * Public-facing AI agent on the homepage. Visitors fill an intro form,
 * chat with an AI assistant powered by the admin-configured provider keys
 * (Settings → AI Providers), and every conversation is captured as a
 * HomepageLead row that the admin can review under /admin/homepage-leads.
 *
 * No workspace coupling — leads are admin-scoped by design so any team
 * member with admin access can triage them regardless of workspace.
 */
class HomepageAgentController extends Controller
{
    public function __construct(private HomepageAgentService $agent)
    {
    }

    public function start(Request $request): JsonResponse
    {
        $data = $request->validate([
            'name'     => ['required', 'string', 'max:120'],
            'email'    => ['nullable', 'email', 'max:255'],
            'company'  => ['nullable', 'string', 'max:160'],
            'use_case' => ['nullable', 'string', 'in:pricing,demo,features,support,other'],
            'page_url' => ['nullable', 'string', 'max:500'],
        ]);

        if (! $this->agent->isReady()) {
            return response()->json([
                'success' => false,
                'message' => __('The AI agent is not configured. Please set an API key under Admin → AI Providers.'),
            ], 503);
        }

        $lead = HomepageLead::create([
            'session_id' => (string) Str::uuid(),
            'name'       => trim($data['name']),
            'email'      => ! empty($data['email']) ? strtolower(trim($data['email'])) : null,
            'company'    => $data['company'] ?? null,
            'use_case'   => $data['use_case'] ?? null,
            'page_url'   => $data['page_url'] ?? null,
            'ip_address' => $request->ip(),
            'user_agent' => substr((string) $request->userAgent(), 0, 500),
            'transcript' => [],
            'status'     => HomepageLead::STATUS_NEW,
        ]);

        $request->session()->put('agent_session_id', $lead->session_id);

        return response()->json([
            'success' => true,
            'data' => [
                'session_id' => $lead->session_id,
                'greeting'   => SystemSetting::get(
                    'agent_homepage_greeting',
                    __("Hi! I'm here to help. Ask me anything or tell me what you're looking for.")
                ),
            ],
        ]);
    }

    public function send(Request $request): JsonResponse
    {
        $data = $request->validate([
            'message' => ['required', 'string', 'max:2000'],
        ]);

        $sessionId = $request->session()->get('agent_session_id');
        if (! $sessionId) {
            return response()->json([
                'success' => false,
                'message' => __('Session expired. Please start a new chat.'),
            ], 401);
        }

        $lead = HomepageLead::where('session_id', $sessionId)->first();
        if (! $lead) {
            return response()->json([
                'success' => false,
                'message' => __('Conversation not found.'),
            ], 404);
        }

        $body = trim($data['message']);

        // Persist the visitor turn before calling the LLM so we never lose it
        $lead->appendMessage('user', $body);
        $lead->save();

        try {
            $reply = $this->agent->generateReply($body, $lead);
        } catch (\Throwable $e) {
            Log::error('Homepage agent reply failed', [
                'lead_id' => $lead->id,
                'error'   => $e->getMessage(),
            ]);

            $fallback = __("I'm having trouble responding right now. A team member will follow up shortly — feel free to leave more details.");
            $lead->appendMessage('agent', $fallback);
            $lead->save();

            return response()->json([
                'success' => true,
                'data' => [
                    'user_message' => ['id' => 'u-'.Str::uuid(), 'role' => 'user',  'body' => $body],
                    'agent_reply'  => ['id' => 'a-'.Str::uuid(), 'role' => 'agent', 'body' => $fallback, 'is_fallback' => true],
                ],
            ]);
        }

        $lead->appendMessage('agent', $reply['content']);
        $lead->ai_provider   = $reply['provider'];
        $lead->ai_model      = $reply['model'];
        $lead->ai_tokens_in  = (int) $lead->ai_tokens_in  + $reply['tokens_in'];
        $lead->ai_tokens_out = (int) $lead->ai_tokens_out + $reply['tokens_out'];
        $lead->ai_total_cost = (float) $lead->ai_total_cost + $reply['cost'];
        $lead->save();

        return response()->json([
            'success' => true,
            'data' => [
                'user_message' => ['id' => 'u-'.Str::uuid(), 'role' => 'user',  'body' => $body],
                'agent_reply'  => ['id' => 'a-'.Str::uuid(), 'role' => 'agent', 'body' => $reply['content']],
            ],
        ]);
    }

    public function history(Request $request): JsonResponse
    {
        $sessionId = $request->session()->get('agent_session_id');
        if (! $sessionId) {
            return response()->json(['success' => true, 'data' => ['messages' => []]]);
        }

        $lead = HomepageLead::where('session_id', $sessionId)->first();
        if (! $lead) {
            return response()->json(['success' => true, 'data' => ['messages' => []]]);
        }

        $messages = collect($lead->transcript ?? [])
            ->map(fn ($entry, $idx) => [
                'id'   => 'h-'.$idx,
                'role' => ($entry['role'] ?? '') === 'user' ? 'user' : 'agent',
                'body' => (string) ($entry['content'] ?? ''),
            ])
            ->values();

        return response()->json([
            'success' => true,
            'data' => [
                'messages' => $messages,
                'status'   => $lead->status,
            ],
        ]);
    }

    public function reset(Request $request): JsonResponse
    {
        $request->session()->forget('agent_session_id');
        return response()->json(['success' => true]);
    }
}
