<?php
namespace App\Neuron;

use NeuronAI\Agent;
use NeuronAI\Providers\AIProviderInterface;
use NeuronAI\Providers\Gemini\Gemini;
use NeuronAI\SystemPrompt;
use NeuronAI\Chat\History\ChatHistoryInterface;
use NeuronAI\Chat\History\FileChatHistory;
use NeuronAI\MCP\McpConnector;
use App\Neuron\KnowledgeRetriever;
use App\Neuron\ToolRetriever;
use Dotenv\Dotenv;

class Goo extends Agent
{
    protected string $conversationId;
    protected string $userPrompt;
    protected ?ToolRetriever $toolRetriever = null;

    public function __construct(string $conversationId, string $userPrompt = '')
    {
        if (!isset($_ENV['AI_API_KEY'])) {
            $dotenv = \Dotenv\Dotenv::createImmutable(__DIR__);
            $dotenv->safeLoad();
        }
        
        $this->conversationId = $conversationId;
        $this->userPrompt = $userPrompt;
        
        // Initialize tool retriever
        $key = $_ENV['AI_API_KEY'] ?? getenv('AI_API_KEY');
        $this->toolRetriever = new ToolRetriever($key);
    }

    protected function provider(): AIProviderInterface
    {
        $key = $_ENV['AI_API_KEY'] ?? getenv('AI_API_KEY');

        return new Gemini(
            key: $key,
            model: 'gemini-3-flash-preview',
        );
    }

    public function instructions(): string
    {
        return (string) new SystemPrompt(
            background: [
                "You are an Employee Portal assistant with access to company databases and documentation.",
                "CRITICAL TOOL USAGE RULES:",
                "1. NEVER make up database queries or pretend to access data - always use the provided tools",
                "2. ONLY use tools that are actually available in your tool list - never reference non-existent tools",
                "3. For documentation questions (how-to, procedures), use the manual context provided below",
                "4. When user asks for data WITHOUT explicitly requesting Excel/chart output, use ONLY the database query tool",
                "5. Excel/chart generation tools should ONLY be used when user explicitly asks for: 'create excel', 'export to excel', 'make a chart', 'visualize', 'generate report file'",
                "6. CRITICAL: When a chart generation tool returns data with 'html_content', you MUST return the ENTIRE tool output as-is in your response. Do NOT summarize or describe it - just return the raw JSON tool result.",
                "7. CRITICAL: When an Excel generation tool returns success, you must output EXACTLY: 'EXCEL_RESULT:' followed by the complete JSON tool output on the same line, then on a new line say 'Your Excel file has been created and is ready to download.'",
                "",
                "Available capabilities:",
                "- Database query tools for customer complaints and other records",
                "- User manual knowledge for procedures and how-to questions",
                $this->manualContext()
            ],
        );
    }
    
    protected function chatHistory(): ChatHistoryInterface
    {
        return new FileChatHistory(
            __DIR__ . '/Chats',
            key: $this->conversationId,
            contextWindow: 50000
        );
    }

    /**
     * Retrieve relevant knowledge from user manual based on semantic similarity
     */
    protected function manualContext(): string
    {
        if (empty($this->userPrompt)) return "";

        $key = $_ENV['AI_API_KEY'] ?? getenv('AI_API_KEY');
        $retriever = new KnowledgeRetriever($key);

        try {
            $docs = $retriever->getRelevantKnowledge($this->userPrompt, 3);
            $minScore = 0.50;
            $docs = array_filter($docs, fn($d) => $d['score'] >= $minScore);

            if (empty($docs)) {
                return "";
            }

            $contextText = "\n\n**Relevant User Manual Information:**\n";

            foreach ($docs as $doc) {
                $contextText .= "\n---\n";
                $contextText .= "**{$doc['title']}**\n";
                $contextText .= "{$doc['content']->load()}\n";
            }

            return $contextText;
        } catch (\Exception $e) {
            // If knowledge retrieval fails, continue without it
            return "";
        }
    }

    /**
     * Intelligently load only relevant tools based on semantic similarity
     */
    protected function tools(): array
    {
        if (empty($this->userPrompt)) {
            return [];
        }

        // Skip tool loading for simple greetings
        $trimmed = trim($this->userPrompt);
        $simpleGreetings = ['hi', 'hello', 'hey', 'hi there', 'hello there', 'good morning', 'good afternoon'];
        if (in_array(strtolower($trimmed), $simpleGreetings)) {
            return [];
        }
        
        try {
            // Load MCP server first
            $serverPath = __DIR__ . '/MCP/Server.php';
            if (!file_exists($serverPath)) {
                return [];
            }
            
            $connector = McpConnector::make([
                'command' => 'php',
                'args' => [$serverPath],
            ]);
            
            $allTools = $connector->tools();
            
            // Safety check: ensure we got an array
            if (!is_array($allTools) || empty($allTools)) {
                return [];
            }
            
            // Detect if user explicitly wants Excel/Chart output
            $outputKeywords = ['excel', 'export', 'download', 'file', 'spreadsheet', 'chart', 'graph', 
                              'visualize', 'plot', 'report file', 'generate file', 'create file'];
            $wantsOutput = false;
            
            foreach ($outputKeywords as $keyword) {
                if (stripos($this->userPrompt, $keyword) !== false) {
                    $wantsOutput = true;
                    break;
                }
            }
            
            // Filter out Excel/Chart tools if user doesn't explicitly want them
            if (!$wantsOutput) {
                $allTools = array_filter($allTools, function($tool) {
                    $toolName = strtolower(method_exists($tool, 'getName') ? $tool->getName() : '');
                    
                    // Exclude Excel and Chart generation tools
                    $excludePatterns = ['excel', 'chart', 'create_excel', 'generate_chart', 'generate_simple_chart',
                                       'generate_comparison_chart', 'generate_trend_chart', 'create_excel_report'];
                    
                    foreach ($excludePatterns as $pattern) {
                        if (stripos($toolName, $pattern) !== false) {
                            return false;
                        }
                    }
                    return true;
                });
            }
            
            // Use semantic search to find relevant tools
            $relevantTools = $this->toolRetriever->getRelevantTools($this->userPrompt, 10);
            $minToolScore = 0.40;
            
            $relevantTools = array_filter($relevantTools, fn($t) => $t['score'] >= $minToolScore);
            
            // Keyword-based fallback for database queries
            $databaseKeywords = ['get', 'fetch', 'find', 'show', 'list', 'query', 'data', 'record', 
                                'complaint', 'customer', 'order', 'table', 'database', 'latest', 'recent',
                                'top', 'most', 'count', 'how many'];
            
            $hasDatabaseKeyword = false;
            foreach ($databaseKeywords as $keyword) {
                if (stripos($this->userPrompt, $keyword) !== false) {
                    $hasDatabaseKeyword = true;
                    break;
                }
            }
            
            // If no semantic match but has database keywords, 
            // include tools with database-related names
            if (empty($relevantTools) && $hasDatabaseKeyword) {
                $dbToolPatterns = ['customer', 'complaint', 'order', 'database', 'query', 'data', 'get_'];
                
                $filteredTools = array_filter($allTools, function($tool) use ($dbToolPatterns) {
                    // Get tool name (not class name)
                    $toolName = strtolower(method_exists($tool, 'getName') ? $tool->getName() : '');
                    
                    foreach ($dbToolPatterns as $pattern) {
                        if (stripos($toolName, $pattern) !== false) {
                            return true;
                        }
                    }
                    return false;
                });
                
                // Return database-related tools (max 5) or all if still empty
                $result = !empty($filteredTools) ? array_slice($filteredTools, 0, 5) : $allTools;
                return array_values($result); // Re-index
            }
            
            // If we have semantic matches, filter tools
            if (!empty($relevantTools)) {
                $relevantToolClasses = array_column($relevantTools, 'class');
                
                $filteredTools = array_filter($allTools, function($tool) use ($relevantToolClasses) {
                    // Get both tool name AND check against class patterns
                    $toolName = strtolower(method_exists($tool, 'getName') ? $tool->getName() : '');
                    
                    foreach ($relevantToolClasses as $className) {
                        // Extract simple class name from full path
                        $simpleClassName = strtolower(basename(str_replace('\\', '/', $className)));
                        
                        // Match if tool name contains class pattern or vice versa
                        if (stripos($toolName, $simpleClassName) !== false || 
                            stripos($simpleClassName, $toolName) !== false ||
                            stripos($className, $toolName) !== false) {
                            return true;
                        }
                    }
                    return false;
                });
                
                // Return filtered tools (max 10) or fallback to top 5 tools
                $result = !empty($filteredTools) ? array_slice($filteredTools, 0, 10) : array_slice($allTools, 0, 5);
                return array_values($result); // Re-index
            }
            
            // Default: return empty, let AI respond conversationally
            return [];
            
        } catch (\Exception $e) {
            // Log error if needed
            error_log("Tool loading error: " . $e->getMessage());
            return [];
        }
    }
}