<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;
use App\Models\AiDocumentChunk;

class DiagnoseOllama extends Command
{
    protected $signature = 'ollama:diagnose';
    protected $description = 'Diagnose Ollama connectivity and embedding issues';

    public function handle()
    {
        $ollamaUrl = config('ollama.base_url', 'http://172.16.1.6:11434');
        
        $this->info("Diagnosing Ollama at: {$ollamaUrl}");
        
        // Test 1: Check connectivity
        $this->info("\n1. Testing connectivity...");
        try {
            $response = Http::timeout(5)->get("{$ollamaUrl}/api/tags");
            if ($response->successful()) {
                $this->info("✓ Ollama is reachable");
                $models = collect($response->json('models'))->pluck('name');
                $this->info("Available models: " . $models->implode(', '));
            } else {
                $this->error("✗ Ollama responded with error: " . $response->status());
            }
        } catch (\Exception $e) {
            $this->error("✗ Cannot reach Ollama: " . $e->getMessage());
            return 1;
        }
        
        // Test 2: Test embedding generation
        $this->info("\n2. Testing embedding generation...");
        try {
            $response = Http::timeout(60)->post("{$ollamaUrl}/api/embeddings", [
                'model' => 'nomic-embed-text',
                'prompt' => 'This is a test sentence.'
            ]);
            
            if ($response->successful()) {
                $data = $response->json();
                if (isset($data['embedding'])) {
                    $this->info("✓ Embedding generated successfully");
                    $this->info("Embedding size: " . count($data['embedding']));
                } else {
                    $this->error("✗ No embedding in response");
                }
            } else {
                $this->error("✗ Embedding request failed: " . $response->body());
            }
        } catch (\Exception $e) {
            $this->error("✗ Embedding error: " . $e->getMessage());
        }
        
        // Test 3: Check database
        $this->info("\n3. Checking database chunks...");
        $totalChunks = AiDocumentChunk::count();
        $withEmbeddings = AiDocumentChunk::whereNotNull('embedding')
            ->where('embedding', '!=', '')
            ->where('embedding', '!=', '[]')
            ->count();
            
        $this->info("Total chunks: {$totalChunks}");
        $this->info("Chunks with embeddings: {$withEmbeddings}");
        $this->info("Chunks missing embeddings: " . ($totalChunks - $withEmbeddings));
        
        return 0;
    }
}