<?php

namespace Modules\VetAI\Entities;

use Illuminate\Database\Eloquent\Model;

class VaiSetting extends Model
{
    protected $table = 'vai_settings';
    protected $guarded = ['id'];

    protected $casts = [
        'api_key'                    => 'encrypted',
        't_api_key'                  => 'encrypted',
        'enabled'                    => 'boolean',
        'use_separate_transcription' => 'boolean',
        'auto_structure_soap'        => 'boolean',
        'consent_warning'            => 'boolean',
        't_clean_non_medical'        => 'boolean',
    ];

    /** Get (or lazily create) the AI settings row for a business. */
    public static function forBusiness($businessId): self
    {
        return static::firstOrCreate(
            ['business_id' => $businessId],
            ['provider' => 'anthropic', 'enabled' => false]
        );
    }

    /** Ready to make AI calls? */
    public function isConfigured(): bool
    {
        if (!$this->enabled || empty($this->model)) {
            return false;
        }
        // openai_compatible needs an endpoint; the API key is optional (e.g. local Ollama).
        if ($this->provider === 'openai_compatible') {
            return !empty($this->base_url);
        }
        return !empty($this->api_key);
    }

    /** Default model suggestion per provider. */
    public static function defaultModel(string $provider): string
    {
        return [
            'anthropic' => 'claude-haiku-4-5-20251001',
            'openai'    => 'gpt-4o-mini',
            'gemini'    => 'gemini-1.5-flash',
        ][$provider] ?? '';
    }

    /**
     * Returns the (provider, base_url, api_key, model, language) tuple that
     * should be used for VOICE transcription. When use_separate_transcription
     * is false it falls back to the main assistant credentials (so a single
     * OpenAI-compatible setup powers both the text AI and Whisper).
     */
    public function transcriptionConfig(): array
    {
        if ($this->use_separate_transcription) {
            return [
                'provider' => $this->t_provider     ?: 'webspeech',
                'base_url' => $this->t_base_url     ?: null,
                'api_key'  => $this->t_api_key      ?: null,
                'model'    => $this->t_model        ?: 'whisper-large-v3-turbo',
                'language' => $this->t_language_hint ?: 'auto',
            ];
        }
        // Reuse the main assistant credentials.
        // Only OpenAI-compatible providers can transcribe; everything else
        // degrades to the browser's built-in Web Speech API.
        $reusableProviders = ['openai', 'openai_compatible'];
        if (!in_array($this->provider, $reusableProviders, true)) {
            return [
                'provider' => 'webspeech',
                'base_url' => null, 'api_key' => null,
                'model'    => null, 'language' => 'auto',
            ];
        }
        return [
            'provider' => $this->provider === 'openai' ? 'whisper_openai' : 'whisper_openai_compat',
            'base_url' => $this->base_url ?: 'https://api.openai.com/v1',
            'api_key'  => $this->api_key,
            'model'    => 'whisper-1',
            'language' => 'auto',
        ];
    }

    /** Is voice transcription configured and ready to use? */
    public function isTranscriptionConfigured(): bool
    {
        $cfg = $this->transcriptionConfig();
        if ($cfg['provider'] === 'webspeech') return true;
        if (empty($cfg['model'])) return false;
        if ($cfg['provider'] === 'whisper_openai_compat') {
            return !empty($cfg['base_url']);
        }
        return !empty($cfg['api_key']);
    }

    public static function providers(): array
    {
        return ['anthropic', 'openai', 'gemini', 'openai_compatible'];
    }

    public static function transcriptionProviders(): array
    {
        return [
            'webspeech'             => 'Browser Web Speech (free, runs on-device)',
            'whisper_openai'        => 'OpenAI Whisper (whisper-1)',
            'whisper_groq'          => 'Groq Whisper (whisper-large-v3-turbo — cheap)',
            'whisper_openai_compat' => 'Self-hosted / OpenAI-compatible endpoint',
        ];
    }
}
