<?php

namespace Modules\VetAI\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Str;
use Modules\VetAI\Entities\VaiSetting;
use Modules\VetAI\Services\AiClient;

class VaiSettingsController extends Controller
{
    private function biz()
    {
        return request()->session()->get('user.business_id');
    }

    private function gate()
    {
        if (!auth()->user()->can('vet_ai.manage_settings')) {
            abort(403, 'Unauthorized action.');
        }
    }

    public function index()
    {
        $this->gate();
        $settings = VaiSetting::forBusiness($this->biz());
        return view('vetAI::settings.index', compact('settings'));
    }

    public function save(Request $request)
    {
        $this->gate();
        $request->validate([
            'provider' => 'required|in:anthropic,openai,gemini,openai_compatible',
            'model'    => 'nullable|string|max:100',
            'base_url' => 'nullable|string|max:255',
        ]);

        $settings = VaiSetting::forBusiness($this->biz());

        $data = [
            'provider'             => $request->provider,
            'base_url'             => $request->provider === 'openai_compatible' ? ($request->base_url ?: null) : null,
            'model'                => $request->model ?: VaiSetting::defaultModel($request->provider),
            'enabled'              => $request->boolean('enabled'),
            'temperature'          => min(1, max(0, (float) ($request->temperature ?? 0.3))),
            'max_tokens'           => min(8192, max(256, (int) ($request->max_tokens ?? 1024))),
            'system_prompt'        => $request->filled('system_prompt') ? $request->system_prompt : null,
            'monthly_token_budget' => $request->monthly_token_budget ?: null,
        ];

        // Only overwrite the stored key when a real new value is submitted.
        if ($request->filled('api_key') && $request->api_key !== '••••••••') {
            $data['api_key'] = trim($request->api_key);
        }

        // ── Voice transcription block ─────────────────────────────────
        $data['use_separate_transcription'] = $request->boolean('use_separate_transcription');
        $data['auto_structure_soap']        = $request->boolean('auto_structure_soap');
        $data['consent_warning']            = $request->boolean('consent_warning');
        // Silence tolerance applies even when transcription provider is the
        // default webspeech, so keep it outside the provider-specific guard.
        $data['t_silence_limit_sec']        = max(5, min(300, (int) ($request->t_silence_limit_sec ?: 30)));
        // Non-medical stripping uses the main assistant LLM, not the
        // voice provider - so it works regardless of webspeech vs whisper.
        $data['t_clean_non_medical']        = $request->boolean('t_clean_non_medical');
        if ($data['use_separate_transcription']) {
            $tProviders = array_keys(VaiSetting::transcriptionProviders());
            $tp = in_array($request->t_provider, $tProviders, true) ? $request->t_provider : 'webspeech';
            $data['t_provider']      = $tp;
            $data['t_base_url']      = $tp === 'whisper_openai_compat' ? ($request->t_base_url ?: null) : null;
            $data['t_model']         = $request->t_model ?: null;
            $data['t_language_hint'] = $request->t_language_hint ?: 'auto';
            if ($request->filled('t_api_key') && $request->t_api_key !== '••••••••') {
                $data['t_api_key'] = trim($request->t_api_key);
            }
        }

        $settings->update($data);

        return redirect()->route('vai.settings.index')
            ->with('status', ['success' => 1, 'msg' => __('vetAI::lang.saved')]);
    }

    /** Test connectivity against the currently-saved provider/key/model. */
    public function test()
    {
        $this->gate();
        $settings = VaiSetting::forBusiness($this->biz());

        if (empty($settings->api_key) || empty($settings->model)) {
            return response()->json(['success' => false, 'msg' => __('vetAI::lang.test_needs_save')]);
        }

        $res = app(AiClient::class)->chat(
            $settings,
            'You are a connectivity test endpoint.',
            'Reply with exactly the two letters: OK'
        );

        return response()->json([
            'success' => $res['ok'],
            'msg'     => $res['ok']
                ? ('Connection OK — model replied: "' . Str::limit(trim($res['text']), 60) . '"')
                : ('Failed: ' . $res['error']),
        ]);
    }
}
