<?php

namespace Modules\AiCore\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\AiCore\Entities\AiProvider;
use Modules\AiCore\Entities\Services\AiClient;

/**
 * Shared, business-type-aware AI helper endpoints reusable across modules.
 */
class AiToolsController extends Controller
{
    /**
     * Interpret a set of laboratory results. Business-type-aware (the persona +
     * subject come from the AI Settings "Business Type"), so the same endpoint
     * serves the vet analyzer (NX600Lab) and the human clinic (ClinicLab).
     * Stateless: it only analyses the results POSTed by the page the user is
     * already viewing — no cross-record DB lookups.
     */
    public function interpretLab(Request $request)
    {
        $request->validate([
            'results'        => 'required|array|min:1|max:150',
            'results.*.test' => 'required|string|max:120',
            'context'        => 'nullable|string|max:600',
        ]);

        $businessId = (int) $request->session()->get('user.business_id');
        if (!$businessId) {
            return response()->json(['success' => false, 'msg' => 'No business in session.'], 422);
        }
        $settings = AiProvider::forBusiness($businessId, 'default');
        if (!$settings->isConfigured()) {
            return response()->json(['success' => false, 'msg' => 'AI is not configured. Open AI Settings.'], 422);
        }
        $vp = $settings->vertical();

        $lines = collect($request->input('results', []))->map(function ($r) {
            $s = (string) ($r['test'] ?? '');
            if (isset($r['value']) && $r['value'] !== '') $s .= ': ' . $r['value'];
            if (!empty($r['unit'])) $s .= ' ' . $r['unit'];
            if (!empty($r['ref']))  $s .= ' (ref ' . $r['ref'] . ')';
            if (!empty($r['flag'])) $s .= ' [' . $r['flag'] . ']';
            return trim($s);
        })->filter()->implode("\n- ");

        $system = "You are an {$vp->assistant} reviewing laboratory results for a " . mb_strtolower($vp->label) . " {$vp->subject}. "
            . "Given the results below (with reference ranges and abnormal flags), produce a concise, conservative clinical interpretation: what the abnormal values most likely indicate, their significance taken together, and the recommended next steps / further tests. "
            . "Use ONLY the data provided; never invent results or values. This is decision-support only — a qualified professional must confirm.\n\n"
            . "Output STRICTLY a JSON object: {\"concern\":\"low|moderate|high\",\"summary\":\"<2-4 sentences>\",\"notes\":[{\"test\":\"<analyte>\",\"note\":\"<short interpretation>\"}]}.";
        $user = ($request->filled('context') ? 'PATIENT CONTEXT: ' . $request->input('context') . "\n\n" : '')
            . "LAB RESULTS:\n- " . $lines;

        // Read-only + deterministic for identical results — safe to short-TTL cache
        // (re-opening the same panel returns instantly and spends no tokens).
        $res = (new AiClient())->chat($settings, $system, $user, ['module' => 'AiCore', 'feature' => 'lab_interpret', 'cacheable' => true]);
        if (empty($res['ok'])) {
            return response()->json(['success' => false, 'msg' => $res['error'] ?? 'AI request failed.'], 502);
        }
        $clean = preg_replace('/^```(?:json)?\s*|\s*```$/m', '', trim((string) ($res['text'] ?? '')));
        $parsed = json_decode($clean, true);
        if (!is_array($parsed)) {
            return response()->json(['success' => true, 'concern' => 'unknown', 'summary' => trim((string) ($res['text'] ?? '')), 'notes' => []]);
        }
        $concern = in_array(($parsed['concern'] ?? ''), ['low', 'moderate', 'high'], true) ? $parsed['concern'] : 'unknown';
        $notes = [];
        foreach ((array) ($parsed['notes'] ?? []) as $n) {
            if (!is_array($n)) continue;
            $notes[] = [
                'test' => mb_substr((string) ($n['test'] ?? ''), 0, 80),
                'note' => mb_substr((string) ($n['note'] ?? ''), 0, 300),
            ];
        }
        return response()->json([
            'success' => true,
            'concern' => $concern,
            'summary' => mb_substr((string) ($parsed['summary'] ?? ''), 0, 800),
            'notes'   => $notes,
        ]);
    }
}
