<?php
/**
 * Document Analysis Service
 *
 * Analyzes user messages to detect intent to create WordPress posts/documents.
 * Migrated from integrations/openai/Integration.php
 *
 * @package FleekDash\AI\Services
 * @since 2.3.0
 */

namespace FleekDash\AI\Services;

use FleekDash\AI\Core\AIProviderManager;

defined('ABSPATH') || exit;

/**
 * Class DocumentAnalysisService
 *
 * Handles intelligent document creation detection and analysis.
 */
class DocumentAnalysisService
{
    /**
     * Analyze user message to determine if document should be created
     *
     * @param string $message User message
     * @return array Analysis result with should_create, title, needs_clarification, confidence
     */
    public static function analyzeDocumentRequest(string $message): array
    {
        // Use AI to analyze intent instead of rigid patterns
        $intent_analysis = self::analyzeIntentWithAI($message);

        return [
            'should_create' => $intent_analysis['should_create'] ?? false,
            'title' => $intent_analysis['title'] ?? '',
            'needs_clarification' => $intent_analysis['needs_clarification'] ?? false,
            'confidence' => $intent_analysis['confidence'] ?? 1,
        ];
    }

    /**
     * Use AI to intelligently analyze user intent
     *
     * @param string $message User message
     * @return array Intent analysis result
     */
    protected static function analyzeIntentWithAI(string $message): array
    {
        try {
            $providerManager = AIProviderManager::getInstance();
            $provider = $providerManager->getActiveProvider();

            if (!$provider || !$provider->isConfigured()) {
                // Fallback if no provider available
                return self::fallbackIntentAnalysis($message);
            }

            // Create a simple intent analysis prompt
            $intent_prompt = "Analyze this user message and determine if they want to create content (post, page, document, article, etc.) in WordPress.

User message: \"{$message}\"

Respond with ONLY a JSON object in this exact format:
{
    \"should_create\": true/false,
    \"title\": \"extracted topic/title\",
    \"needs_clarification\": true/false,
    \"confidence\": 1-3,
    \"reasoning\": \"brief explanation\"
}

Rules:
- If user says \"create a post about X\", \"write about X\", \"make content about X\" → should_create: true
- Extract the main topic as title (clean, no extra words)
- If unclear or ambiguous → needs_clarification: true
- Confidence: 3=very clear, 2=somewhat clear, 1=unclear
- Be generous - if user mentions creating/writing content, assume they want it created";

            $response = $provider->chat([
                [
                    'role' => 'system',
                    'content' => 'You are an intent analysis assistant. Always respond with valid JSON only.'
                ],
                [
                    'role' => 'user',
                    'content' => $intent_prompt
                ]
            ], [
                'model' => 'gpt-3.5-turbo',
                'temperature' => 0.1,
                'max_tokens' => 200
            ]);

            if (isset($response['content'])) {
                $content = $response['content'];

                // Clean the response (remove any extra text)
                $json_start = strpos($content, '{');
                $json_end = strrpos($content, '}');

                if ($json_start !== false && $json_end !== false) {
                    $json_content = substr($content, $json_start, $json_end - $json_start + 1);
                    $result = json_decode($json_content, true);

                    if ($result && isset($result['should_create'])) {
                        return $result;
                    }
                }
            }
        } catch (\Exception $e) {
            // Silently fallback if AI intent analysis fails
            error_log('[DocumentAnalysisService] AI analysis failed: ' . $e->getMessage());
        }

        // Fallback to simple pattern matching if AI fails
        return self::fallbackIntentAnalysis($message);
    }

    /**
     * Simple fallback analysis if AI fails
     *
     * @param string $message User message
     * @return array Fallback analysis result
     */
    protected static function fallbackIntentAnalysis(string $message): array
    {
        // Very basic patterns as fallback
        if (preg_match('/create\s+(?:a\s+)?(?:post|page|document|article)\s+about\s+(.+)/i', $message, $matches)) {
            return [
                'should_create' => true,
                'title' => trim($matches[1]),
                'needs_clarification' => false,
                'confidence' => 3,
                'reasoning' => 'fallback pattern match'
            ];
        }

        if (preg_match('/(?:write|make|create)\s+(?:about|on)\s+(.+)/i', $message, $matches)) {
            return [
                'should_create' => true,
                'title' => trim($matches[1]),
                'needs_clarification' => false,
                'confidence' => 2,
                'reasoning' => 'fallback pattern match'
            ];
        }

        return [
            'should_create' => false,
            'title' => '',
            'needs_clarification' => true,
            'confidence' => 1,
            'reasoning' => 'no clear intent detected'
        ];
    }

    /**
     * Detect target post type from user message
     *
     * @param string $message User message
     * @return string Post type slug
     */
    public static function detectTargetPostType(string $message): string
    {
        $m = strtolower($message);
        $availableTypes = self::collectAvailablePostTypeNames();
        $cues = self::buildPostTypeCues();

        $resolved = self::matchPostTypeFromCues($m, $cues);
        if ($resolved === null) {
            $resolved = self::matchPostTypeFromRegisteredLabels($m, $availableTypes);
        }
        if ($resolved === null) {
            $resolved = \post_type_exists('fleekdash_document') ? 'fleekdash_document' : 'post';
        }

        return $resolved;
    }

    /**
     * Get post type label
     *
     * @param string $post_type Post type slug
     * @return string Post type label
     */
    public static function getPostTypeLabel(string $post_type): string
    {
        $fixedLabels = [
            'post' => 'Post',
            'page' => 'Page',
            'product' => 'Product',
            'article' => 'Article',
        ];
        if (isset($fixedLabels[$post_type])) {
            return $fixedLabels[$post_type];
        }

        $post_type_obj = \get_post_type_object($post_type);
        $label = 'Post';
        if ($post_type_obj !== null && isset($post_type_obj->labels->singular_name)) {
            $label = $post_type_obj->labels->singular_name;
        }

        return $label;
    }

    /**
     * Get site context information for AI
     *
     * @return string Site context string
     */
    public static function getSiteContext(): string
    {
        // WordPress global functions
        $site_url = \get_site_url();
        $site_name = \get_bloginfo('name');
        $site_description = \get_bloginfo('description');
        $site_admin_email = \get_option('admin_email');

        // Get additional site information
        $site_tagline = \get_bloginfo('tagline');
        $site_language = \get_bloginfo('language');
        $site_version = \get_bloginfo('version');

        // Get theme information
        $theme = wp_get_theme();
        $theme_name = $theme->get('Name');
        $theme_description = $theme->get('Description');

        // Get user information
        $current_user = \wp_get_current_user();
        $user_name = $current_user ? $current_user->display_name : 'Guest';
        $user_first_name = 'Guest';
        if ($current_user && $current_user->ID) {
            $meta_first = \get_user_meta($current_user->ID, 'first_name', true);
            if (is_string($meta_first) && $meta_first !== '') {
                $user_first_name = $meta_first;
            } else {
                $parts = explode(' ', $user_name);
                $user_first_name = $parts[0] ?? $user_name;
            }
        }
        $user_role = $current_user ? ($current_user->roles[0] ?? 'subscriber') : 'guest';

        // Get site categories and tags for content context
        $categories = \get_categories(['hide_empty' => false, 'number' => 10]);
        $tags = \get_tags(['hide_empty' => false, 'number' => 10]);

        $context = "SITE INFORMATION:\n";
        $context .= "- Site URL: {$site_url}\n";
        $context .= "- Site Name: {$site_name}\n";
        $context .= "- Site Description: {$site_description}\n";
        $context .= "- Site Tagline: {$site_tagline}\n";
        $context .= "- Site Language: {$site_language}\n";
        $context .= "- Site Admin Email: {$site_admin_email}\n";
        $context .= "- WordPress Version: {$site_version}\n";
        $context .= "- Theme: {$theme_name} ({$theme_description})\n";
        $context .= "- Current User: {$user_name} (Role: {$user_role})\n";
        $context .= "- User First Name: {$user_first_name}\n";

        if (!empty($categories)) {
            $context .= "- Main Categories: " . implode(', ', array_slice(array_map(function ($cat) {
                return $cat->name;
            }, $categories), 0, 5)) . "\n";
        }

        if (!empty($tags)) {
            $context .= "- Popular Tags: " . implode(', ', array_slice(array_map(function ($tag) {
                return $tag->name;
            }, $tags), 0, 5)) . "\n";
        }

        $context .= "\nCONTEXT FOR AI: Use this information to provide more relevant and contextual responses. ";
        $context .= "Consider the site's theme, categories, and user role when generating content or suggestions. ";
        $context .= "Address the user by their first name naturally (1-2 times max per response) to keep it friendly and personal.";

        return $context;
    }

    /**
     * Public + custom post type names used when matching the message to a type.
     *
     * @return array<int, string>
     */
    private static function collectAvailablePostTypeNames(): array
    {
        $available_types = \get_post_types(['public' => true], 'names');
        $additional = ['product', 'page', 'post'];
        if (\post_type_exists('fleekdash_document')) {
            $additional[] = 'fleekdash_document';
        }

        return array_unique(array_merge($available_types, $additional));
    }

    /**
     * Keyword cues per post type (fleekdash_document prioritized over generic post when registered).
     *
     * @return array<string, array<int, string>>
     */
    private static function buildPostTypeCues(): array
    {
        $cues = [];
        $cues['product'] = ['product', 'produto', 'woocommerce'];
        $cues['page'] = ['page', 'pagina', 'landing page'];
        if (\post_type_exists('fleekdash_document')) {
            $cues['fleekdash_document'] = ['document', 'doc', 'documento'];
        }
        $post_keywords = ['post', 'blog', 'article', 'artigo'];
        if (!\post_type_exists('fleekdash_document')) {
            $post_keywords = array_merge($post_keywords, ['document', 'doc', 'documento']);
        }
        $cues['post'] = $post_keywords;

        return $cues;
    }

    /**
     * @param array<string, array<int, string>> $cues
     */
    private static function matchPostTypeFromCues(string $m, array $cues): ?string
    {
        foreach ($cues as $type => $keywords) {
            if (!\post_type_exists($type)) {
                continue;
            }
            foreach ($keywords as $kw) {
                if (strpos($m, $kw) !== false) {
                    return $type;
                }
            }
        }

        return null;
    }

    /**
     * @param array<int, string> $available_types
     */
    private static function matchPostTypeFromRegisteredLabels(string $m, array $available_types): ?string
    {
        foreach ($available_types as $type) {
            if (strpos($m, strtolower($type)) !== false && \post_type_exists($type)) {
                return $type;
            }
        }

        return null;
    }
}
