<?php
/**
 * AI Tool Scanner
 *
 * Detects AI plugins and third-party AI scripts on the WordPress site.
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Tiriri_Scanner {

    /**
     * Database of known AI plugin slugs
     * Format: 'plugin-slug/main-file.php' => array of metadata
     */
    private function get_known_ai_plugins() {
        return array(
            // AI Chatbots
            'tidio-live-chat/tidio-live-chat.php' => array(
                'name'     => 'Tidio - Live Chat & AI Chatbots',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI chatbot interacts directly with visitors.',
            ),
            'tawk-to-live-chat/tawkto.php' => array(
                'name'     => 'Tawk.to Live Chat',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI-powered chat features require disclosure.',
            ),
            'smartsupp-live-chat/smartsupp.php' => array(
                'name'     => 'Smartsupp Live Chat',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI chatbot component requires disclosure.',
            ),
            'crisp/crisp.php' => array(
                'name'     => 'Crisp – Live Chat & Chatbot',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI chatbot requires disclosure when active.',
            ),
            'livechat-woocommerce/livechat-woocommerce.php' => array(
                'name'     => 'LiveChat – WooCommerce Live Chat',
                'category' => 'chatbot',
                'risk'     => 'may_require_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI features in chatbot may require disclosure.',
            ),
            'zendesk/zendesk.php' => array(
                'name'     => 'Zendesk Chat',
                'category' => 'chatbot',
                'risk'     => 'may_require_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI Answer Bot requires disclosure if enabled.',
            ),
            'jivochat/jivochat.php' => array(
                'name'     => 'JivoChat Live Chat',
                'category' => 'chatbot',
                'risk'     => 'may_require_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI features require disclosure when enabled.',
            ),

            // AI Content Generation
            'ai-engine/ai-engine.php' => array(
                'name'     => 'AI Engine',
                'category' => 'content_generation',
                'risk'     => 'requires_labeling',
                'article'  => '50(2), 50(4)',
                'note'     => 'AI-generated content must be labeled. Chatbot feature requires disclosure.',
            ),
            'jetpack/jetpack.php' => array(
                'name'     => 'Jetpack (AI Assistant)',
                'category' => 'content_generation',
                'risk'     => 'may_require_labeling',
                'article'  => '50(2), 50(4)',
                'note'     => 'AI Assistant generates content that may need labeling.',
            ),
            'flavor/flavor.php' => array(
                'name'     => 'flavor - AI Content Generator',
                'category' => 'content_generation',
                'risk'     => 'requires_labeling',
                'article'  => '50(2), 50(4)',
                'note'     => 'AI-generated content must be labeled.',
            ),
            'starter-templates/starter-templates.php' => array(
                'name'     => 'Starter Templates – AI Website Builder',
                'category' => 'content_generation',
                'risk'     => 'may_require_labeling',
                'article'  => '50(2)',
                'note'     => 'AI-generated website content may need labeling.',
            ),
            'ai-content-writing-assistant/developer_flavor_ai.php' => array(
                'name'     => 'AI Content Writing Assistant',
                'category' => 'content_generation',
                'risk'     => 'requires_labeling',
                'article'  => '50(2), 50(4)',
                'note'     => 'AI-generated text must be labeled.',
            ),
            'getgenie/getgenie.php' => array(
                'name'     => 'GetGenie AI',
                'category' => 'content_generation',
                'risk'     => 'requires_labeling',
                'article'  => '50(2), 50(4)',
                'note'     => 'AI-generated content must be labeled.',
            ),
            'writebot-ai/writebot-ai.php' => array(
                'name'     => 'WriterBot AI',
                'category' => 'content_generation',
                'risk'     => 'requires_labeling',
                'article'  => '50(2), 50(4)',
                'note'     => 'AI-generated content must be labeled.',
            ),

            // AI SEO Tools (with content generation features)
            'wordpress-seo/wp-seo.php' => array(
                'name'     => 'Yoast SEO (AI Features)',
                'category' => 'seo_ai',
                'risk'     => 'may_require_labeling',
                'article'  => '50(2)',
                'note'     => 'AI-generated titles and meta descriptions may need labeling if published.',
            ),
            'seo-by-rank-math/rank-math.php' => array(
                'name'     => 'Rank Math SEO (AI Features)',
                'category' => 'seo_ai',
                'risk'     => 'may_require_labeling',
                'article'  => '50(2)',
                'note'     => 'Content AI features generate text that may need labeling.',
            ),
            'all-in-one-seo-pack/all_in_one_seo_pack.php' => array(
                'name'     => 'All in One SEO (AI Features)',
                'category' => 'seo_ai',
                'risk'     => 'may_require_labeling',
                'article'  => '50(2)',
                'note'     => 'AI-powered title and description generation.',
            ),

            // AI Image Generation
            'flavor/flavor-image.php' => array(
                'name'     => 'Flavor - AI Image Generator',
                'category' => 'image_generation',
                'risk'     => 'requires_labeling',
                'article'  => '50(2)',
                'note'     => 'AI-generated images must be labeled.',
            ),
            'gpt3-ai-content-generator/gpt3-ai-content-generator.php' => array(
                'name'     => 'AI Power - Complete AI Pack',
                'category' => 'image_generation',
                'risk'     => 'requires_labeling',
                'article'  => '50(2)',
                'note'     => 'AI-generated images and content must be labeled.',
            ),

            // Page Builders with AI
            'elementor/elementor.php' => array(
                'name'     => 'Elementor (AI Features)',
                'category' => 'page_builder_ai',
                'risk'     => 'may_require_labeling',
                'article'  => '50(2)',
                'note'     => 'Elementor AI generates text, images, and code. Generated content may need labeling.',
            ),

            // AI Translation
            'translatepress-multilingual/index.php' => array(
                'name'     => 'TranslatePress (AI Translation)',
                'category' => 'translation_ai',
                'risk'     => 'low_risk',
                'article'  => '50(2)',
                'note'     => 'AI translation is generally considered assistive editing (exception under Article 50(2)).',
            ),
            'weglot/weglot.php' => array(
                'name'     => 'Weglot Translate',
                'category' => 'translation_ai',
                'risk'     => 'low_risk',
                'article'  => '50(2)',
                'note'     => 'AI translation is generally considered assistive editing.',
            ),

            // AI Product Recommendations (WooCommerce)
            'woocommerce/woocommerce.php' => array(
                'name'     => 'WooCommerce (AI Features)',
                'category' => 'ecommerce_ai',
                'risk'     => 'may_require_disclosure',
                'article'  => '50(1), 50(2)',
                'note'     => 'AI product recommendations and AI-generated descriptions may need disclosure.',
            ),
        );
    }

    /**
     * Known third-party AI script signatures (embedded via JavaScript)
     */
    private function get_known_ai_scripts() {
        return array(
            array(
                'pattern'  => 'intercom.io',
                'name'     => 'Intercom AI',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'Intercom Fin AI Agent requires disclosure.',
            ),
            array(
                'pattern'  => 'drift.com',
                'name'     => 'Drift AI',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'Drift AI chatbot requires disclosure.',
            ),
            array(
                'pattern'  => 'crisp.chat',
                'name'     => 'Crisp Chat',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'Crisp AI features require disclosure.',
            ),
            array(
                'pattern'  => 'collect.chat',
                'name'     => 'Collect.chat AI',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI chatbot requires disclosure.',
            ),
            array(
                'pattern'  => 'kommunicate.io',
                'name'     => 'Kommunicate AI',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI chatbot requires disclosure.',
            ),
            array(
                'pattern'  => 'chatbase.co',
                'name'     => 'Chatbase AI',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'Custom ChatGPT chatbot requires disclosure.',
            ),
            array(
                'pattern'  => 'botpress.cloud',
                'name'     => 'Botpress AI',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI chatbot requires disclosure.',
            ),
            array(
                'pattern'  => 'voiceflow.com',
                'name'     => 'Voiceflow AI',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI assistant requires disclosure.',
            ),
            array(
                'pattern'  => 'ada.cx',
                'name'     => 'Ada AI',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI customer service agent requires disclosure.',
            ),
            array(
                'pattern'  => 'customerly.io',
                'name'     => 'Customerly AI',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI chatbot requires disclosure.',
            ),
            array(
                'pattern'  => 'chatbot.com',
                'name'     => 'ChatBot.com',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI chatbot requires disclosure.',
            ),
            array(
                'pattern'  => 'landbot.io',
                'name'     => 'Landbot AI',
                'category' => 'chatbot',
                'risk'     => 'requires_disclosure',
                'article'  => '50(1)',
                'note'     => 'AI chatbot requires disclosure.',
            ),
        );
    }

    /**
     * Initialize scanner hooks
     */
    public function init() {
        // Schedule daily scan
        if ( ! wp_next_scheduled( 'tiriri_daily_scan' ) ) {
            wp_schedule_event( time(), 'daily', 'tiriri_daily_scan' );
        }
        add_action( 'tiriri_daily_scan', array( $this, 'run_scan' ) );

        // Re-scan when plugins are activated or deactivated
        add_action( 'activated_plugin', array( $this, 'run_scan' ) );
        add_action( 'deactivated_plugin', array( $this, 'run_scan' ) );
    }

    /**
     * Run a full scan
     */
    public function run_scan() {
        $results = array(
            'plugins'    => $this->scan_plugins(),
            'scripts'    => array(), // Script scanning happens on frontend
            'manual'     => $this->get_manual_declarations(),
            'scan_time'  => current_time( 'mysql' ),
        );

        update_option( 'tiriri_scan_results', $results );

        return $results;
    }

    /**
     * Layer 1: Scan installed plugins against known AI database
     */
    public function scan_plugins() {
        $active_plugins = get_option( 'active_plugins', array() );
        $known_plugins  = $this->get_known_ai_plugins();
        $detected       = array();

        foreach ( $active_plugins as $plugin ) {
            if ( isset( $known_plugins[ $plugin ] ) ) {
                $info = $known_plugins[ $plugin ];
                $info['slug'] = $plugin;
                $info['source'] = 'plugin_scan';
                $info['disclosure_status'] = $this->get_disclosure_status( $plugin );
                $detected[] = $info;
            }
        }

        // Also check for partial slug matches (some plugins have variant file names)
        foreach ( $active_plugins as $plugin ) {
            $plugin_dir = dirname( $plugin );
            foreach ( $known_plugins as $known_slug => $info ) {
                $known_dir = dirname( $known_slug );
                if ( $plugin_dir === $known_dir && $known_slug !== $plugin ) {
                    $info['slug'] = $plugin;
                    $info['source'] = 'plugin_scan';
                    $info['disclosure_status'] = $this->get_disclosure_status( $plugin );
                    // Avoid duplicates
                    $already_found = false;
                    foreach ( $detected as $d ) {
                        if ( $d['slug'] === $plugin ) {
                            $already_found = true;
                            break;
                        }
                    }
                    if ( ! $already_found ) {
                        $detected[] = $info;
                    }
                }
            }
        }

        return $detected;
    }

    /**
     * Layer 2: Get script patterns for frontend detection
     * (Actual detection happens via JavaScript on the frontend)
     */
    public function get_script_patterns() {
        return $this->get_known_ai_scripts();
    }

    /**
     * Get manually declared AI tools
     */
    public function get_manual_declarations() {
        return get_option( 'tiriri_manual_declarations', array() );
    }

    /**
     * Add a manual AI tool declaration
     */
    public function add_manual_declaration( $declaration ) {
        $declarations = $this->get_manual_declarations();
        $declaration['id'] = wp_generate_uuid4();
        $declaration['source'] = 'manual';
        $declaration['added_date'] = current_time( 'mysql' );
        $declarations[] = $declaration;
        update_option( 'tiriri_manual_declarations', $declarations );
        return $declaration;
    }

    /**
     * Remove a manual declaration
     */
    public function remove_manual_declaration( $id ) {
        $declarations = $this->get_manual_declarations();
        $declarations = array_filter( $declarations, function( $d ) use ( $id ) {
            return $d['id'] !== $id;
        } );
        update_option( 'tiriri_manual_declarations', array_values( $declarations ) );
    }

    /**
     * Get disclosure status for a specific plugin
     */
    private function get_disclosure_status( $plugin_slug ) {
        $disclosures = get_option( 'tiriri_disclosures', array() );
        if ( isset( $disclosures[ $plugin_slug ] ) && $disclosures[ $plugin_slug ]['enabled'] ) {
            return 'active';
        }
        return 'not_configured';
    }

    /**
     * Get overall compliance status
     * Returns: 'compliant', 'partial', 'non_compliant'
     */
    public function get_compliance_status() {
        $results = get_option( 'tiriri_scan_results', array() );

        if ( empty( $results ) || empty( $results['plugins'] ) ) {
            return 'no_ai_detected';
        }

        $total_requiring = 0;
        $total_disclosed = 0;

        foreach ( $results['plugins'] as $plugin ) {
            if ( in_array( $plugin['risk'], array( 'requires_disclosure', 'requires_labeling' ), true ) ) {
                $total_requiring++;
                if ( 'active' === $plugin['disclosure_status'] ) {
                    $total_disclosed++;
                }
            }
        }

        if ( 0 === $total_requiring ) {
            return 'no_action_needed';
        }

        if ( $total_disclosed === $total_requiring ) {
            return 'compliant';
        }

        if ( $total_disclosed > 0 ) {
            return 'partial';
        }

        return 'non_compliant';
    }

    /**
     * Get days until Article 50 enforcement
     */
    public function get_days_until_enforcement() {
        $enforcement_date = strtotime( '2026-08-02' );
        $today = time();
        $diff = $enforcement_date - $today;
        return max( 0, (int) floor( $diff / DAY_IN_SECONDS ) );
    }

    /**
     * Get summary stats for dashboard
     */
    public function get_summary() {
        $results = get_option( 'tiriri_scan_results', array() );
        $plugins = isset( $results['plugins'] ) ? $results['plugins'] : array();
        $manual  = isset( $results['manual'] ) ? $results['manual'] : array();

        $all_tools = array_merge( $plugins, $manual );

        $summary = array(
            'total_detected'       => count( $all_tools ),
            'chatbots'             => 0,
            'content_generators'   => 0,
            'other_ai'             => 0,
            'requiring_disclosure' => 0,
            'disclosed'            => 0,
            'compliance_status'    => $this->get_compliance_status(),
            'days_until_deadline'  => $this->get_days_until_enforcement(),
            'last_scan'            => isset( $results['scan_time'] ) ? $results['scan_time'] : null,
        );

        foreach ( $all_tools as $tool ) {
            if ( 'chatbot' === $tool['category'] ) {
                $summary['chatbots']++;
            } elseif ( in_array( $tool['category'], array( 'content_generation', 'seo_ai', 'image_generation' ), true ) ) {
                $summary['content_generators']++;
            } else {
                $summary['other_ai']++;
            }

            if ( in_array( $tool['risk'], array( 'requires_disclosure', 'requires_labeling' ), true ) ) {
                $summary['requiring_disclosure']++;
                if ( isset( $tool['disclosure_status'] ) && 'active' === $tool['disclosure_status'] ) {
                    $summary['disclosed']++;
                }
            }
        }

        return $summary;
    }
}
