<?php
/**
 * Admin submenu: AI Agents - live credentials + connection probe.
 */

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

add_action('admin_menu', 'askagento_add_agents_mcp_page', 11);

function askagento_add_agents_mcp_page() {
    add_submenu_page(
        'edit.php?post_type=' . ASKAGENTO_POST_TYPE,
        __('AI Agents', 'askagento'),
        __('AI Agents', 'askagento'),
        'manage_options',
        'askagento-agents-mcp',
        'askagento_render_agents_mcp_page',
        null
    );
}

add_action('admin_enqueue_scripts', 'askagento_agents_mcp_enqueue');

function askagento_agents_mcp_enqueue($hook_suffix) {
    if ($hook_suffix !== 'askagento_filter_page_askagento-agents-mcp') {
        return;
    }

    $install    = function_exists('askagento_get_install_settings') ? askagento_get_install_settings() : [];
    $api_url    = isset($install['api_url']) ? rtrim((string) $install['api_url'], '/') : '';
    $api_key    = isset($install['api_key']) ? trim((string) $install['api_key']) : '';
    $site_id    = (string) get_option('askagento_install_site_id', '');
    $mcp_url    = ($api_url !== '' && $site_id !== '' && $api_key !== '')
        ? $api_url . '/mcp'
        : '';

    wp_enqueue_script(
        'askagento-agents-mcp-admin',
        ASKAGENTO_PLUGIN_URL . 'assets/js/admin-agents-mcp.js',
        ['jquery'],
        askagento_asset_version('assets/js/admin-agents-mcp.js'),
        true
    );

    wp_localize_script(
        'askagento-agents-mcp-admin',
        'askagentoAgentsMcp',
        [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce'   => wp_create_nonce('askagento_admin'),
            'mcpUrl'  => $mcp_url,
            'siteId'  => $site_id,
            'apiKey'  => $api_key,
            'i18n'    => [
                'probing'          => __('Running MCP probe...', 'askagento'),
                'failed'           => __('Probe failed.', 'askagento'),
                'notConfigured'    => __('MCP endpoint not configured. Finish installation first.', 'askagento'),
                'copied'           => __('Copied!', 'askagento'),
                'show'             => __('Show', 'askagento'),
                'hide'             => __('Hide', 'askagento'),
                'handshakeSuccess' => __('MCP handshake successful', 'askagento'),
                'protocolVersion'  => __('Protocol version', 'askagento'),
                'server'           => __('Server', 'askagento'),
                'tools'            => __('Tools', 'askagento'),
            ],
        ]
    );
}

/**
 * Render AI Agents admin screen.
 */
function askagento_render_agents_mcp_page() {
    if (!current_user_can('manage_options')) {
        return;
    }

    $install  = function_exists('askagento_get_install_settings') ? askagento_get_install_settings() : [];
    $api_url  = isset($install['api_url']) ? rtrim((string) $install['api_url'], '/') : '';
    $api_key  = isset($install['api_key']) ? trim((string) $install['api_key']) : '';
    $site_id  = (string) get_option('askagento_install_site_id', '');
    $mcp_url  = ($api_url !== '' && $site_id !== '' && $api_key !== '')
        ? $api_url . '/mcp'
        : '';

    $configured = $mcp_url !== '';

    $tab = isset($_GET['tab']) ? sanitize_key((string) wp_unslash($_GET['tab'])) : 'setup'; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
    if ($tab !== 'test') {
        $tab = 'setup';
    }
    $tab_base      = add_query_arg(['post_type' => ASKAGENTO_POST_TYPE, 'page' => 'askagento-agents-mcp'], admin_url('edit.php'));
    $tab_url_setup = add_query_arg('tab', 'setup', $tab_base);
    $tab_url_test  = add_query_arg('tab', 'test',  $tab_base);

    // Cursor config snippet
    $cursor_cfg = wp_json_encode(
        [
            'mcpServers' => [
                'askagento-shop' => [
                    'url'     => $mcp_url ?: ASKAGENTO_API_BASE . '/mcp',
                    'headers' => [
                        'X-Askagento-Site-Id' => $site_id ?: '<your-site-id>',
                        'X-Askagento-Api-Key' => $api_key ?: '<your-api-key>',
                    ],
                ],
            ],
        ],
        JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
    );

    // Claude Desktop config snippet
    $claude_cfg = wp_json_encode(
        [
            'mcpServers' => [
                'askagento-shop' => [
                    'type'    => 'http',
                    'url'     => $mcp_url ?: ASKAGENTO_API_BASE . '/mcp',
                    'headers' => [
                        'X-Askagento-Site-Id' => $site_id ?: '<your-site-id>',
                        'X-Askagento-Api-Key' => $api_key ?: '<your-api-key>',
                    ],
                ],
            ],
        ],
        JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
    );
    ?>
    <div class="wrap askagento-agents-mcp-wrap">
        <h1><?php echo esc_html__('AI Agents', 'askagento'); ?></h1>

        <h2 class="nav-tab-wrapper askagento-agents-mcp-tabs">
            <a href="<?php echo esc_url($tab_url_setup); ?>"
               class="nav-tab<?php echo $tab === 'setup' ? ' nav-tab-active' : ''; ?>"
               id="askagento-agents-mcp-tab-setup-link"
               <?php echo $tab === 'setup' ? 'aria-current="true"' : ''; ?>
            ><?php echo esc_html__('Setup', 'askagento'); ?></a>
            <a href="<?php echo esc_url($tab_url_test); ?>"
               class="nav-tab<?php echo $tab === 'test' ? ' nav-tab-active' : ''; ?>"
               id="askagento-agents-mcp-tab-test-link"
               <?php echo $tab === 'test' ? 'aria-current="true"' : ''; ?>
            ><?php echo esc_html__('Test', 'askagento'); ?></a>
        </h2>

        <!-- ── Setup tab ─────────────────────────────────────────────────── -->
        <div class="askagento-agents-mcp-tab-panel"
             id="askagento-agents-mcp-tab-panel-setup"
             <?php echo $tab !== 'setup' ? 'hidden' : ''; ?>
             role="tabpanel"
             aria-labelledby="askagento-agents-mcp-tab-setup-link">

            <?php if (!$configured) : ?>
            <div class="notice notice-warning inline" style="max-width:820px;">
                <p><?php echo esc_html__('Complete Askagento installation (site registration) before connecting agents.', 'askagento'); ?></p>
            </div>
            <?php endif; ?>

            <div class="askagento-agents-mcp-section">
                <h2><?php echo esc_html__('MCP connection', 'askagento'); ?></h2>
                <p class="description" style="margin-top:0;max-width:56em;">
                    <?php echo esc_html__('Use these credentials to connect any MCP-compatible agent (Cursor, Claude Desktop, OpenAI Agents SDK, etc.) to your shop\'s semantic search and AI assistant.', 'askagento'); ?>
                </p>
                <table class="form-table" role="presentation">
                    <tbody>
                        <tr>
                            <th scope="row"><?php echo esc_html__('MCP endpoint URL', 'askagento'); ?></th>
                            <td>
                                <div class="askagento-mcp-copy-row">
                                    <input type="url" class="large-text code" readonly
                                           value="<?php echo esc_attr($mcp_url ?: '-'); ?>"
                                           id="askagento-mcp-endpoint-field" />
                                    <?php if ($mcp_url) : ?>
                                    <button type="button" class="button askagento-mcp-copy-btn"
                                            data-target="askagento-mcp-endpoint-field">
                                        <?php echo esc_html__('Copy', 'askagento'); ?>
                                    </button>
                                    <?php endif; ?>
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('Site ID', 'askagento'); ?></th>
                            <td>
                                <div class="askagento-mcp-copy-row">
                                    <input type="text" class="regular-text code" readonly
                                           value="<?php echo esc_attr($site_id ?: '-'); ?>"
                                           id="askagento-mcp-siteid-field" />
                                    <?php if ($site_id) : ?>
                                    <button type="button" class="button askagento-mcp-copy-btn"
                                            data-target="askagento-mcp-siteid-field">
                                        <?php echo esc_html__('Copy', 'askagento'); ?>
                                    </button>
                                    <?php endif; ?>
                                </div>
                                <p class="description"><?php echo esc_html__('Sent as the X-Askagento-Site-Id header.', 'askagento'); ?></p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row"><?php echo esc_html__('API key', 'askagento'); ?></th>
                            <td>
                                <div class="askagento-mcp-copy-row">
                                    <input type="password" class="regular-text code" readonly
                                           value="<?php echo esc_attr($api_key ?: '-'); ?>"
                                           id="askagento-mcp-apikey-field" />
                                    <?php if ($api_key) : ?>
                                    <button type="button" class="button askagento-mcp-copy-btn"
                                            data-target="askagento-mcp-apikey-field">
                                        <?php echo esc_html__('Copy', 'askagento'); ?>
                                    </button>
                                    <button type="button" class="button askagento-mcp-reveal-btn"
                                            data-target="askagento-mcp-apikey-field"
                                            data-label-show="<?php echo esc_attr__('Show', 'askagento'); ?>"
                                            data-label-hide="<?php echo esc_attr__('Hide', 'askagento'); ?>">
                                        <?php echo esc_html__('Show', 'askagento'); ?>
                                    </button>
                                    <?php endif; ?>
                                </div>
                                <p class="description"><?php echo esc_html__('Sent as X-Askagento-Api-Key header.', 'askagento'); ?></p>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

            <div class="askagento-agents-mcp-section">
                <h2><?php echo esc_html__('Cursor / Windsurf', 'askagento'); ?></h2>
                <p class="description" style="margin-top:0;max-width:56em;">
                    <?php echo esc_html__('Add to ~/.cursor/mcp.json (or Windsurf equivalent) and reload the IDE.', 'askagento'); ?>
                </p>
                <p style="margin:0 0 8px;">
                    <button type="button" class="button askagento-mcp-snippet-reveal-btn"
                            data-target="askagento-mcp-cursor-snippet-wrap"
                            aria-expanded="false"
                            aria-controls="askagento-mcp-cursor-snippet-wrap">
                        <?php echo esc_html__('Show', 'askagento'); ?>
                    </button>
                </p>
                <div class="askagento-mcp-snippet-wrap" id="askagento-mcp-cursor-snippet-wrap" hidden>
                    <pre class="askagento-mcp-snippet" id="askagento-mcp-cursor-snippet"><?php echo esc_html($cursor_cfg); ?></pre>
                    <button type="button" class="button askagento-mcp-copy-pre-btn"
                            data-target="askagento-mcp-cursor-snippet">
                        <?php echo esc_html__('Copy', 'askagento'); ?>
                    </button>
                </div>
            </div>

            <div class="askagento-agents-mcp-section">
                <h2><?php echo esc_html__('Claude Desktop', 'askagento'); ?></h2>
                <p class="description" style="margin-top:0;max-width:56em;">
                    <?php echo esc_html__('Add to claude_desktop_config.json under the mcpServers key.', 'askagento'); ?>
                </p>
                <p style="margin:0 0 8px;">
                    <button type="button" class="button askagento-mcp-snippet-reveal-btn"
                            data-target="askagento-mcp-claude-snippet-wrap"
                            aria-expanded="false"
                            aria-controls="askagento-mcp-claude-snippet-wrap">
                        <?php echo esc_html__('Show', 'askagento'); ?>
                    </button>
                </p>
                <div class="askagento-mcp-snippet-wrap" id="askagento-mcp-claude-snippet-wrap" hidden>
                    <pre class="askagento-mcp-snippet" id="askagento-mcp-claude-snippet"><?php echo esc_html($claude_cfg); ?></pre>
                    <button type="button" class="button askagento-mcp-copy-pre-btn"
                            data-target="askagento-mcp-claude-snippet">
                        <?php echo esc_html__('Copy', 'askagento'); ?>
                    </button>
                </div>
            </div>

            <div class="askagento-agents-mcp-section">
                <h2><?php echo esc_html__('Available tools', 'askagento'); ?></h2>
                <table class="widefat striped" style="max-width:820px;">
                    <thead>
                        <tr>
                            <th><?php echo esc_html__('Tool', 'askagento'); ?></th>
                            <th><?php echo esc_html__('What it does', 'askagento'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><code>browse_products</code></td>
                            <td><?php echo esc_html__('Filter catalogue by category, tag, and/or price range. Supports pagination via offset.', 'askagento'); ?></td>
                        </tr>
                        <tr>
                            <td><code>chat_with_shop</code></td>
                            <td><?php echo esc_html__('Conversational shop assistant with product context. Supports multi-turn history.', 'askagento'); ?></td>
                        </tr>
                        <tr>
                            <td><code>get_catalogue_stats</code></td>
                            <td><?php echo esc_html__('Orientation summary: product count, price range, category/tag counts, featured and on-sale totals.', 'askagento'); ?></td>
                        </tr>
                        <tr>
                            <td><code>get_featured_products</code></td>
                            <td><?php echo esc_html__('Return featured products, products on sale, or new arrivals (list_type, limit).', 'askagento'); ?></td>
                        </tr>
                        <tr>
                            <td><code>get_product_by_id</code></td>
                            <td><?php echo esc_html__('Full details for one product by its WooCommerce id (title, price, categories, tags, description).', 'askagento'); ?></td>
                        </tr>
                        <tr>
                            <td><code>get_shop_status</code></td>
                            <td><?php echo esc_html__('Install status, billing plan, and remaining token/search quotas.', 'askagento'); ?></td>
                        </tr>
                        <tr>
                            <td><code>get_similar_products</code></td>
                            <td><?php echo esc_html__('Cross-sell and upsell recommendations for one product_id.', 'askagento'); ?></td>
                        </tr>
                        <tr>
                            <td><code>list_categories</code></td>
                            <td><?php echo esc_html__('All product categories with name, slug, and product count. Use before browse_products.', 'askagento'); ?></td>
                        </tr>
                        <tr>
                            <td><code>list_tags</code></td>
                            <td><?php echo esc_html__('All product tags with name, slug, and product count. Use before browse_products.', 'askagento'); ?></td>
                        </tr>
                        <tr>
                            <td><code>search_products</code></td>
                            <td><?php echo esc_html__('Semantic product search by text, image, or both (optional modality, query, image_base64, limit).', 'askagento'); ?></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- ── Test tab ──────────────────────────────────────────────────── -->
        <div class="askagento-agents-mcp-tab-panel"
             id="askagento-agents-mcp-tab-panel-test"
             <?php echo $tab !== 'test' ? 'hidden' : ''; ?>
             role="tabpanel"
             aria-labelledby="askagento-agents-mcp-tab-test-link">

            <div class="askagento-agents-mcp-section">
                <h2><?php echo esc_html__('MCP handshake probe', 'askagento'); ?></h2>
                <p class="description" style="margin-top:0;margin-bottom:12px;max-width:52em;">
                    <?php echo esc_html__('Sends initialize + tools/list to your MCP endpoint and displays the negotiated protocol version and available tools.', 'askagento'); ?>
                </p>
                <p>
                    <button type="button" class="button button-primary" id="askagento-mcp-probe-btn"
                        <?php echo !$configured ? 'disabled' : ''; ?>>
                        <?php echo esc_html__('Run MCP probe', 'askagento'); ?>
                    </button>
                </p>
                <div id="askagento-mcp-probe-result" class="askagento-agents-mcp-probe-result" aria-live="polite"></div>
            </div>

            <div class="askagento-agents-mcp-section">
                <h2><?php echo esc_html__('Test: search products', 'askagento'); ?></h2>
                <p style="margin:0 0 8px;">
                    <label for="askagento-mcp-search-query"><strong><?php echo esc_html__('Query', 'askagento'); ?></strong></label>
                </p>
                <p style="margin:0 0 12px;">
                    <input type="text" id="askagento-mcp-search-query" class="large-text"
                           placeholder="<?php echo esc_attr__('e.g. blue ceramic watch', 'askagento'); ?>"
                           <?php echo !$configured ? 'disabled' : ''; ?> />
                </p>
                <p>
                    <button type="button" class="button button-primary" id="askagento-mcp-search-btn"
                        <?php echo !$configured ? 'disabled' : ''; ?>>
                        <?php echo esc_html__('Search via MCP', 'askagento'); ?>
                    </button>
                </p>
                <div id="askagento-mcp-search-result" class="askagento-agents-mcp-probe-result" aria-live="polite"></div>
            </div>

            <div class="askagento-agents-mcp-section">
                <h2><?php echo esc_html__('Test: chat with shop', 'askagento'); ?></h2>
                <p style="margin:0 0 8px;">
                    <label for="askagento-mcp-chat-message"><strong><?php echo esc_html__('Message', 'askagento'); ?></strong></label>
                </p>
                <p style="margin:0 0 12px;">
                    <textarea id="askagento-mcp-chat-message" class="large-text" rows="3"
                              placeholder="<?php echo esc_attr__('Ask something about your shop...', 'askagento'); ?>"
                              <?php echo !$configured ? 'disabled' : ''; ?>></textarea>
                </p>
                <p>
                    <button type="button" class="button button-primary" id="askagento-mcp-chat-btn"
                        <?php echo !$configured ? 'disabled' : ''; ?>>
                        <?php echo esc_html__('Chat via MCP', 'askagento'); ?>
                    </button>
                </p>
                <div id="askagento-mcp-chat-result" class="askagento-agents-mcp-probe-result" aria-live="polite"></div>
            </div>
        </div>
    </div>

    <style>
        .askagento-agents-mcp-wrap h2.askagento-agents-mcp-tabs.nav-tab-wrapper { margin-top:8px; margin-bottom:0; max-width:960px; }
        .askagento-agents-mcp-wrap .askagento-agents-mcp-section { background:#fff; border:1px solid #dcdcde; padding:16px; margin:0 0 16px; max-width:960px; }
        .askagento-agents-mcp-section h2 { margin-top:0; }
        .askagento-mcp-copy-row { display:flex; align-items:center; gap:8px; flex-wrap:wrap; }
        .askagento-mcp-copy-row input { flex:1 1 300px; min-width:0; }
        .askagento-mcp-snippet-wrap { position:relative; max-width:820px; }
        .askagento-mcp-snippet {
            margin:0 0 8px;
            padding:12px 16px;
            background:#f6f7f7;
            border:1px solid #e0e0e0;
            border-radius:4px;
            overflow-x:auto;
            font-size:12px;
            line-height:1.6;
            white-space:pre;
        }
        .askagento-agents-mcp-probe-result { margin-top:12px; max-width:820px; }
        .askagento-agents-mcp-probe-result p { margin:6px 0; }
        .askagento-mcp-tool-tag {
            display:inline-block;
            padding:2px 8px;
            background:#e8f4fd;
            border:1px solid #b3d9f5;
            border-radius:3px;
            font-family:monospace;
            font-size:12px;
            margin:2px 4px 2px 0;
        }
        .askagento-mcp-success { color:#00a32a; font-weight:600; }
        .askagento-mcp-pre-result {
            margin:8px 0 0;
            padding:10px 14px;
            background:#f6f7f7;
            border:1px solid #e0e0e0;
            border-radius:4px;
            font-size:13px;
            white-space:pre-wrap;
            word-break:break-word;
            max-height:320px;
            overflow-y:auto;
        }
    </style>
    <?php
}
