<?php
/**
 * LLM7.io Provider
 * Free AI models compatible with OpenAI API
 */

if ( ! defined( 'ABSPATH' ) ) exit; // Thoát nếu truy cập trực tiếp

class AIAutotool_AI_Provider_LLM7 extends AIAutotool_AI_Provider_Base {
    
    protected $name = 'LLM7.io';
    protected $id = 'llm7';
    protected $base_url = 'https://api.llm7.io/v1';
    protected $default_model = 'default';
    
    protected $available_models = array(
        'default' => 'Default (AgentRouter - Recommended)',
        'fast' => 'Fast (Quick responses)',
        'pro' => 'Pro (Best quality)',
    );
    
    public function __construct($api_key = '') {
        parent::__construct($api_key);
        
        if (empty($this->api_key)) {
            $this->api_key = AIAutotool_API_Manager::get_llm7_key();
        }
        
        // LLM7 uses "unused" as default free tier key
        if (empty($this->api_key)) {
            $this->api_key = 'unused';
        }
    }
    
    /**
     * Chat completion - OpenAI compatible
     */
    public function chat_completion($messages, $options = array()) {
        if (!$this->is_configured()) {
            return array(
                'success' => false,
                'error' => 'LLM7 API key not configured'
            );
        }
        
        $options = $this->parse_options($options);
        
        $url = $this->base_url . '/chat/completions';
        
        $body = array(
            'model' => $options['model'],
            'messages' => $messages,
            'temperature' => floatval($options['temperature']),
            'max_tokens' => intval($options['max_tokens']),
            'top_p' => floatval($options['top_p'])
        );
        
        $headers = array(
            'Authorization' => 'Bearer ' . $this->api_key,
            'Content-Type' => 'application/json'
        );
        
        $this->log('Chat completion request', array('model' => $options['model']));
        
        $response = $this->make_request($url, $body, 'POST', $headers);
        
        if (!$response['success']) {
            return $response;
        }
        
        $data = $response['data'];
        
        return array(
            'success' => true,
            'content' => $data['choices'][0]['message']['content'],
            'usage' => isset($data['usage']) ? $data['usage'] : null,
            'model' => $data['model'],
            'finish_reason' => $data['choices'][0]['finish_reason']
        );
    }
    
    /**
     * Test connection
     */
    public function test_connection() {
        if (!$this->is_configured()) {
            return array(
                'success' => false,
                'message' => 'LLM7 API key not configured'
            );
        }
        
        $url = $this->base_url . '/models';
        
        $headers = array(
            'Authorization' => 'Bearer ' . $this->api_key,
            'Content-Type' => 'application/json'
        );
        
        $response = $this->make_request($url, null, 'GET', $headers);
        
        if ($response['success']) {
            $model_count = is_array($response['data']) ? count($response['data']) : 0;
            return array(
                'success' => true,
                'message' => sprintf('LLM7 API connection successful! Found %d models.', $model_count)
            );
        } else {
            return array(
                'success' => false,
                'message' => 'LLM7 API Error: ' . $response['error']
            );
        }
    }
    
    /**
     * Get models list
     */
    public function get_models() {
        if (!$this->is_configured()) {
            return array(
                'success' => false,
                'error' => 'LLM7 API key not configured'
            );
        }
        
        $url = $this->base_url . '/models';
        
        $headers = array(
            'Authorization' => 'Bearer ' . $this->api_key,
            'Content-Type' => 'application/json'
        );
        
        $response = $this->make_request($url, null, 'GET', $headers);
        
        if ($response['success'] && is_array($response['data'])) {
            $models = array();
            foreach ($response['data'] as $model) {
                if (isset($model['id'])) {
                    $models[] = $model['id'];
                }
            }
            
            return array(
                'success' => true,
                'models' => $models
            );
        }
        
        return $response;
    }
    
    /**
     * Check if configured (LLM7 always has at least "unused" key)
     */
    public function is_configured() {
        return !empty($this->api_key);
    }
}

