<?php
/**
 * Plugin Name: Nietos AI
 * Plugin URI: https://nietos.ai
 * Description: AI-powered WordPress assistant for content management and site administration
 * Version: 1.0.0
 * Requires at least: 6.0
 * Requires PHP: 8.0
 * Author: Nietos AI Team
 * License: GPL v2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: nietos-ai
 * Domain Path: /languages
 */

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

// Define plugin constants
define('NIETOS_AI_VERSION', '1.0.0');
define('NIETOS_AI_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('NIETOS_AI_PLUGIN_URL', plugin_dir_url(__FILE__));
define('NIETOS_AI_PLUGIN_FILE', __FILE__);

// Debug mode - set to true to enable detailed logging
if (!defined('NIETOS_AI_DEBUG')) {
    define('NIETOS_AI_DEBUG', true);
}

// Require Composer autoloader if available
if (file_exists(NIETOS_AI_PLUGIN_DIR . 'vendor/autoload.php')) {
    require_once NIETOS_AI_PLUGIN_DIR . 'vendor/autoload.php';
}

// Include core classes
require_once NIETOS_AI_PLUGIN_DIR . 'includes/class-nietos-ai.php';
require_once NIETOS_AI_PLUGIN_DIR . 'includes/class-security.php';
require_once NIETOS_AI_PLUGIN_DIR . 'includes/class-settings.php';
require_once NIETOS_AI_PLUGIN_DIR . 'includes/class-license.php';
require_once NIETOS_AI_PLUGIN_DIR . 'includes/class-premium.php';
require_once NIETOS_AI_PLUGIN_DIR . 'includes/class-api-handler.php';
require_once NIETOS_AI_PLUGIN_DIR . 'includes/class-rest-controller.php';
require_once NIETOS_AI_PLUGIN_DIR . 'includes/class-pattern-support.php';
require_once NIETOS_AI_PLUGIN_DIR . 'admin/class-admin-page.php';
require_once NIETOS_AI_PLUGIN_DIR . 'admin/class-editor-integration.php';

/**
 * Initialize the plugin
 */
function nietos_ai_init() {
    // Run migrations
    nietos_ai_run_migrations();

    // Initialize pattern support
    new Nietos_AI_Pattern_Support();

    $plugin = new Nietos_AI();
    $plugin->run();
}
add_action('plugins_loaded', 'nietos_ai_init');

/**
 * Run database migrations
 */
function nietos_ai_run_migrations() {
    $current_version = get_option('nietos_ai_db_version', '0');

    // Migration 1.0.2: Migrate from Claude to OpenAI
    if (version_compare($current_version, '1.0.2', '<')) {
        $settings = get_option('nietos_ai_settings');

        if ($settings) {
            // Remove api_provider field if it exists
            if (isset($settings['api_provider'])) {
                unset($settings['api_provider']);
            }

            // Update model to OpenAI default if it was a Claude model
            if (isset($settings['model'])) {
                if (strpos($settings['model'], 'claude') !== false) {
                    $settings['model'] = 'gpt-4o';
                }
            }

            update_option('nietos_ai_settings', $settings);
        }

        update_option('nietos_ai_db_version', '1.0.2');
    }
}

/**
 * Activation hook
 */
function nietos_ai_activate() {
    // Set default options
    if (!get_option('nietos_ai_settings')) {
        add_option('nietos_ai_settings', array(
            'api_key' => '',
            'model' => 'gpt-4o',
            'max_tokens' => 4096,
            'temperature' => 0.7
        ));
    }

    // Create prompts directory and files if they don't exist
    $prompts_dir = NIETOS_AI_PLUGIN_DIR . 'prompts';
    if (!file_exists($prompts_dir . '/system-prompt.md')) {
        nietos_ai_create_default_prompts();
    }

    // Flush rewrite rules
    flush_rewrite_rules();
}
register_activation_hook(__FILE__, 'nietos_ai_activate');

/**
 * Deactivation hook
 */
function nietos_ai_deactivate() {
    flush_rewrite_rules();
}
register_deactivation_hook(__FILE__, 'nietos_ai_deactivate');

/**
 * Create default prompt files
 */
function nietos_ai_create_default_prompts() {
    $prompts_dir = NIETOS_AI_PLUGIN_DIR . 'prompts';

    // Ensure directory structure exists
    if (!file_exists($prompts_dir)) {
        wp_mkdir_p($prompts_dir);
    }

    $instructions_dir = trailingslashit($prompts_dir) . 'instructions';
    $examples_dir = trailingslashit($prompts_dir) . 'examples';

    wp_mkdir_p($instructions_dir);
    wp_mkdir_p($examples_dir);

    // Default prompt contents (lightweight fallbacks)
    $defaults = array(
        trailingslashit($prompts_dir) . 'system-prompt.md' =>
'# Nietos AI (Fallback Prompt)

Use the real WordPress tool calls to satisfy every request. Never pretend.

## Core Safety Rules
- Confirm destructive actions (delete, publish, deactivate) before executing.
- Keep existing content structure unless the user explicitly wants changes.
- Use lookup tools when IDs are missing; never guess.
- After making changes, verify with the matching `get_*` tool before reporting success.
- If something fails, be transparent and share manual recovery steps.

## Block Pattern Workflow (Mandatory)
1. Call `list_block_patterns()` before inserting any pattern.
2. Choose 3–5 relevant patterns; apply the first with `mode="replace"`, others with `mode="append"`.
3. Customize placeholder copy via `update_post_blocks()`.
4. Validate with `get_post_blocks()`.

## Links
Always format links as `[text](URL)` — never show bare URLs.',
        trailingslashit($instructions_dir) . 'content.md' => '# Content Operations (Fallback)

Tools: `find_posts`, `create_post`, `update_post`, `get_post_blocks`, `update_post_blocks`, `list_block_patterns`, `apply_block_pattern`, `delete_post`.

1. **Scope the request** – confirm titles, languages, statuses before acting.
2. **Editing** – fetch current blocks with `get_post_blocks()` (or `get_post_content()` if available) before modifying. Write updates with `update_post_blocks()` and re-verify.
3. **Creating** – default to drafts; supply meaningful starter content; share edit links.
4. **Destructive actions** – recap the impact, ask for confirmation, then perform the tool call.
5. **Translations** – change text only, keep block structure intact.'
,
        trailingslashit($instructions_dir) . 'media.md' => '# Media Operations (Fallback)

Tools: `find_media`, `upload_media`, `update_media_metadata`, `set_featured_image`.

- Validate URLs and file types before uploads; create concise alt text automatically.
- Reference attachments by ID and mention where they are used.
- When setting a featured image, confirm the target post and note any previous image replacement.
- For metadata updates, show the current value, change only specified fields, and confirm the outcome.'
,
        trailingslashit($instructions_dir) . 'users.md' => '# User Operations (Fallback)

Tools: `create_user`, `update_user`, `change_user_role`, `delete_user`.

- Check capabilities before continuing (e.g., `create_users`, `promote_user`).
- Confirm key details (email, role, reassignment target) out loud before executing.
- Warn about security implications when elevating roles or deleting accounts.
- Require explicit confirmation for destructive actions and call `delete_user` with `confirm: true`.'
,
        trailingslashit($instructions_dir) . 'settings.md' => '# Settings Operations (Fallback)

Tools: `update_site_settings`, `update_discussion_settings`.

- Show old and new values when changing site title, tagline, timezone, or formats.
- Validate timezones and format strings; reject invalid inputs with suggestions.
- Remind users that some settings may take caching into account.'
,
        trailingslashit($instructions_dir) . 'taxonomy.md' => '# Taxonomy Operations (Fallback)

Tools: `create_term`, `update_term`, `delete_term`, `assign_terms_to_post`.

- Confirm taxonomy and term identity (ID + name). Offer to look up IDs when missing.
- Explain whether terms will be appended or replace the existing set.
- Warn before deleting terms that have assignments and require explicit confirmation.'
,
        trailingslashit($instructions_dir) . 'comments.md' => '# Comment Operations (Fallback)

Tools: `approve_comment`, `trash_comment`, `reply_to_comment`.

- Quote a snippet of the comment, author, and related post before acting.
- Require a yes/no confirmation for moderation or deletion requests.
- When replying, draft text first, confirm tone, then post.'
,
        trailingslashit($instructions_dir) . 'widgets.md' => '# Widget Operations (Fallback)

Tools: `create_widget`, `update_widget`, `delete_widget`, `assign_widget_to_sidebar`.

- Reference widgets by ID (e.g., `text-3`) and sidebars by slug.
- Preserve existing settings when updating; change only requested fields.
- Offer to move widgets to `wp_inactive_widgets` instead of deleting outright.'
,
        trailingslashit($instructions_dir) . 'menus.md' => '# Menu Operations (Fallback)

Tools: `create_menu`, `update_menu`, `delete_menu`, `assign_menu_location`, `add_menu_item`, `update_menu_item`, `delete_menu_item`.

- Identify menus by both name and ID and explain impacts before changes.
- Clarify positions and hierarchy when adding or moving items.
- Confirm destructive actions (deleting menus/items) with the user.'
,
        trailingslashit($instructions_dir) . 'plugins.md' => '# Plugin Operations (Fallback)

Tools: `activate_plugin`, `deactivate_plugin`.

- Mention the exact plugin path (`folder/plugin.php`) before acting.
- Warn about potential site impact and require confirmation, especially for deactivation.
- Remind users to test critical flows after changing plugin states.'
,
        trailingslashit($examples_dir) . 'safety-rules.md' => '# Safety Rules (Fallback)

- Confirm destructive actions and explain consequences.
- Respect WordPress capabilities—stop if the current user lacks permission.
- Never expose secrets (API keys, passwords, private data).
- Be transparent about failures or partial work and offer manual follow-up steps.'
,
    );

    foreach ($defaults as $path => $content) {
        if (!file_exists($path)) {
            file_put_contents($path, $content);
        }
    }
}

/**
 * Load plugin text domain for translations
 * Note: Since WordPress 4.6+, language packs are automatically loaded from WordPress.org
 * No need to manually call load_plugin_textdomain() for plugins hosted on WordPress.org
 */
