<?php
require_once '../config/ai.php';

abstract class BaseAIService {
    protected $client;
    protected $config;

    public function __construct() {
        $this->client = getOpenAIClient();
        $this->config = getAIConfig();
    }

    /**
     * Make a request to OpenAI API with error handling and rate limiting
     */
    protected function makeRequest($messages, $options = []) {
        // Check rate limiting
        if (!checkAIRateLimit($_SESSION['user_id'] ?? null)) {
            throw new Exception('AI rate limit exceeded. Please try again later.');
        }

        // Check if feature is enabled
        if (!$this->isFeatureEnabled()) {
            throw new Exception('AI feature is currently disabled.');
        }

        $defaultOptions = [
            'model' => OPENAI_MODEL,
            'messages' => $messages,
            'max_tokens' => OPENAI_MAX_TOKENS,
            'temperature' => OPENAI_TEMPERATURE,
        ];

        $options = array_merge($defaultOptions, $options);

        $retries = 0;
        while ($retries < AI_MAX_RETRIES) {
            try {
                $response = $this->client->chat()->create($options);

                // Log the request
                $this->logRequest($response, $options);

                return $response;
            } catch (Exception $e) {
                $retries++;
                if ($retries >= AI_MAX_RETRIES) {
                    throw new Exception('AI service temporarily unavailable: ' . $e->getMessage());
                }
                usleep(AI_RETRY_DELAY * 1000); // Convert to microseconds
            }
        }
    }

    /**
     * Log AI request for analytics
     */
    protected function logRequest($response, $options) {
        $tokens = $response->usage->totalTokens ?? 0;
        $cost = $this->calculateCost($tokens);

        logAIRequest(
            $this->getFeatureName(),
            $_SESSION['user_id'] ?? null,
            $tokens,
            $cost
        );
    }

    /**
     * Calculate approximate cost based on tokens
     */
    protected function calculateCost($tokens) {
        // GPT-4o pricing: $0.01 per 1K input tokens, $0.03 per 1K output tokens
        // Simplified calculation
        return ($tokens / 1000) * 0.02; // Average cost
    }

    /**
     * Check if the AI feature is enabled
     */
    abstract protected function isFeatureEnabled();

    /**
     * Get the feature name for logging
     */
    abstract protected function getFeatureName();

    /**
     * Validate input data
     */
    abstract protected function validateInput($data);
}
?>