<?php

/**
 * LolaCore � Activation
 *
 * @package LolaCore
 * @license GPL-2.0-or-later
 */

declare(strict_types=1);

namespace LolaCore;

// phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared, WordPress.DB.DirectDatabaseQuery.SchemaChange, WordPress.DB.SlowDBQuery.slow_db_query_meta_key -- Required for core functionality, dynamic queries, and performance. Validated inputs.

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use LolaCore\Database\Schema;
use LolaCore\Scanner\ScanDataCollector;
use LolaCore\Scanner\SiteScanner;
use LolaCore\Memory\MemoryManager;

class Activation
{
    /**
     * Run activation procedures.
     */
    public static function run(): void
    {
        // Guard: Minimum PHP Version
        if (version_compare(PHP_VERSION, '8.0.0', '<')) {
            wp_die(
                esc_html(
                    sprintf(
                        /* translators: %s: current PHP version */
                        __('LolaCore requires PHP version 8.0.0 or higher. You are running %s', 'lolacore'),
                        PHP_VERSION
                    )
                )
            );
        }

        // Guard: Minimum WordPress Version
        global $wp_version;
        if (version_compare($wp_version, '7.0', '<')) {
            wp_die(
                esc_html(
                    sprintf(
                        /* translators: %s: current WordPress version */
                        __('LolaCore requires WordPress version 7.0 or higher. You are running %s', 'lolacore'),
                        $wp_version
                    )
                )
            );
        }

        // Ensure Schema exists
        require_once __DIR__ . '/Database/Schema.php';
        Schema::create();

        // Seed default configuration
        self::seedDefaultConfig();

        // Note: onboarding_complete is seeded to '0' via INSERT IGNORE in
        // seedDefaultConfig(). On fresh installs, this triggers the welcome
        // sequence. On reactivation/updates, the existing '1' is preserved
        // so that onboarding never replays.
        global $wpdb;

        // Defer the initial scan to the next request.
        // Running it inside register_activation_hook can capture inconsistent
        // state (e.g. lolacore itself missing from active_plugins) depending
        // on the activation flow. The deferred scan runs on 'init' once the
        // site is fully bootstrapped.
        update_option('lolacore_pending_initial_scan', true);

        // Register WP-Cron events
        if (!wp_next_scheduled('lolacore_daily_decay')) {
            wp_schedule_event(time(), 'daily', 'lolacore_daily_decay');
        }

        if (!wp_next_scheduled('lolacore_log_cleanup')) {
            wp_schedule_event(time(), 'daily', 'lolacore_log_cleanup');
        }

        // Update activation time
        update_option('lolacore_activated_at', current_time('mysql'));
        update_option('lolacore_db_version', LOLACORE_DB_VERSION);


    }

    /**
     * Execute the deferred initial site scan.
     *
     * Called from the 'init' hook (see lolacore.php) once a flag set during
     * activation is detected. By running here, active_plugins and other
     * options are guaranteed to be fully persisted.
     */
    public static function runInitialScan(): void
    {
        $collector = new ScanDataCollector();
        $memoryManager = new MemoryManager();
        $scanner = new SiteScanner($collector, $memoryManager);

        $scanner->runFullScan();
    }

    /**
     * Seed the 14 default configuration keys.
     */
    private static function seedDefaultConfig(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'lolacore_config';

        $defaults = [
            'llm_provider'               => '',
            'llm_model'                  => '',
            'api_key'                    => '',
            'technical_level'            => 'technical',
            'onboarding_complete'        => '0',
            'first_real_greeting_done'   => '0',
            'initial_scan'               => '',
            'last_session_summary'       => '',
            'memory_decay_rate'          => '0.02',
            'memory_decay_threshold'     => '0.10',
            'memory_max_context_entries' => '20',
            'log_retention_days'         => '90',
            'hub_node_id'                => wp_generate_uuid4(),
            'hub_connection_status'      => 'disconnected',
        ];

        foreach ($defaults as $key => $value) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.PreparedSQL.NotPrepared -- Custom LolaCore table query.
            $wpdb->query(
                $wpdb->prepare(
                    "INSERT IGNORE INTO {$table} (config_key, config_value) VALUES (%s, %s)",
                    $key,
                    $value,
                )
            );
        }

        self::purgeLegacyHubKeys();
    }

    /**
     * Remove config keys from the discarded pre-DEC-1 pairing model.
     *
     * Pairing now uses the native Application Passwords flow (sprint C0):
     * there is no site token, no hub public key and no handshake token.
     * Runs on every (re)activation so upgraded sites shed the dead keys.
     */
    private static function purgeLegacyHubKeys(): void
    {
        global $wpdb;
        $table = $wpdb->prefix . 'lolacore_config';

        $legacyKeys = [
            'hub_site_token',
            'hub_public_key',
            'hub_connection_token',
            'hub_connection_token_created',
        ];

        foreach ($legacyKeys as $key) {
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Custom LolaCore table cleanup.
            $wpdb->delete($table, ['config_key' => $key], ['%s']);
        }
    }
}