validate([ 'message' => ['required', 'string', 'max:2000'], 'history' => ['nullable', 'array', 'max:20'], 'history.*.role' => ['nullable', 'string'], 'history.*.text' => ['nullable', 'string'], ]); if (! $afia->enabled()) { return response()->json(['message' => 'Afia is not available right now.'], 503); } try { $reply = $afia->chat(trim($validated['message']), $validated['history'] ?? [], $this->context()); } catch (\Throwable $e) { report($e); return response()->json(['message' => 'Afia could not respond right now. Please try again.'], 502); } return response()->json(['reply' => $reply]); } /** @return array Live email context for grounding. */ private function context(): array { $account = ladill_account(); if (! $account) { return ['signed_in' => 'no']; } $pid = (string) $account->public_id; $ctx = ['signed_in' => 'yes']; try { $mailboxes = app(MailboxClient::class)->forUser($pid); $ctx['mailboxes_total'] = count($mailboxes); $ctx['mailboxes_paid'] = count(array_filter($mailboxes, fn ($m) => (bool) ($m['is_paid'] ?? false))); } catch (\Throwable) { } try { $domains = app(EmailDomainClient::class)->forUser($pid); $ctx['domains_total'] = count($domains); $ctx['domains_verified'] = count(array_filter($domains, fn ($d) => (bool) ($d['active'] ?? $d['verified'] ?? false))); } catch (\Throwable) { } try { $ctx['wallet_balance_ghs'] = number_format(app(BillingClient::class)->balanceMinor($pid) / 100, 2); } catch (\Throwable) { } return $ctx; } }