<?php

namespace AtlasAiDev\Awfah\Admin;

use AtlasAiDev\Awfah\Plugin;

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

class Mcp_Page {

    public function __construct() {
        add_action( 'admin_menu', [ $this, 'register_menu' ] );
    }

    public function register_menu(): void {
        add_submenu_page(
            'ai-workflow-automation-ai-agent-hub',
            __( 'MCP Adapter', 'ai-workflow-automation-ai-agent-hub' ),
            __( 'MCP Adapter', 'ai-workflow-automation-ai-agent-hub' ),
            'manage_options',
            'ai-workflow-automation-ai-agent-hub-mcp',
            [ $this, 'render_page' ]
        );
    }

    public function render_page(): void {
        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }

        $saved = false;
        if ( 'POST' === $_SERVER['REQUEST_METHOD'] ) {
            $saved = $this->handle_form_submission();
        }

        $settings   = Plugin::get_mcp_settings();
        $abilities  = Plugin::get_available_mcp_abilities();
        $rest_route = $settings['namespace'] . '/' . $settings['route'];
        $http_url   = rest_url( $rest_route );

        // Default redirect URI points to the REST callback.
        if ( empty( $settings['oauth']['redirect_uri'] ) ) {
            $settings['oauth']['redirect_uri'] = rest_url( 'awfah/v1/mcp/oauth/callback' );
        }

        $authorize_url        = '';
        $authorize_url_notice = '';

        if ( ! empty( $settings['oauth']['client_id'] ) && ! empty( $settings['oauth']['auth_url'] ) ) {
            $auth_base = trim( (string) $settings['oauth']['auth_url'] );

            // Only proceed if the authorization URL looks valid.
            if ( preg_match( '#^https?://#i', $auth_base ) ) {
            $state = wp_generate_password( 24, false, false );
            set_transient( 'ai_agent_hub_oauth_state_' . $state, 1, 10 * MINUTE_IN_SECONDS );
            $authorize_url = add_query_arg(
                array_filter(
                    [
                        'response_type' => 'code',
                        'client_id'     => $settings['oauth']['client_id'],
                        'redirect_uri'  => $settings['oauth']['redirect_uri'],
                        'scope'         => $settings['oauth']['scopes'],
                        'state'         => $state,
                    ]
                ),
                    $auth_base
            );
            } else {
                $authorize_url_notice = __( 'Add a full Authorization URL (https://...) before starting OAuth.', 'ai-workflow-automation-ai-agent-hub' );
            }
        } else {
            $authorize_url_notice = __( 'Enter Client ID and Authorization URL to start OAuth.', 'ai-workflow-automation-ai-agent-hub' );
        }

        $path_hint     = defined( 'ABSPATH' ) ? untrailingslashit( ABSPATH ) : '/path/to/wordpress';
        $stdio_command = sprintf(
            'wp mcp-adapter serve --path=%s --user=YOUR-ADMIN --server=%s',
            $path_hint,
            $settings['server_id']
        );
        $remote_env = [
            'WP_API_URL'      => $http_url,
            'WP_API_USERNAME' => 'your-username',
            'WP_API_PASSWORD' => 'your-application-password',
        ];
        $remote_env_string = sprintf(
            "WP_API_URL=%s\nWP_API_USERNAME=%s\nWP_API_PASSWORD=%s",
            $remote_env['WP_API_URL'],
            $remote_env['WP_API_USERNAME'],
            $remote_env['WP_API_PASSWORD']
        );
        ?>
        <div class="wrap ai-agent-hub-mcp-page">
            <h1><?php esc_html_e( 'MCP Adapter', 'ai-workflow-automation-ai-agent-hub' ); ?></h1>
            <p class="description">
                <?php esc_html_e( 'Expose AI Agent Hub abilities as Model Context Protocol tools. Configure the server, copy the URLs/commands, and lock it down with an optional bearer token.', 'ai-workflow-automation-ai-agent-hub' ); ?>
            </p>
            <style>
                .ai-agent-hub-abilities-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; margin: 8px 0 16px; }
                .ai-agent-hub-ability-card { display: block; border: 1px solid #ccd0d4; border-radius: 6px; padding: 10px; background: #fff; box-shadow: inset 0 1px 0 rgba(255,255,255,.5); }
                .ai-agent-hub-ability-title { display: block; font-weight: 600; }
                .ai-agent-hub-ability-id { display: block; color: #555d66; font-size: 12px; margin-top: 4px; word-break: break-all; }
                .ai-agent-hub-cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); gap: 16px; margin: 10px 0; }
                .ai-agent-hub-cards .card { padding: 14px; }
                .ai-agent-hub-help ol { padding-left: 18px; }
            </style>
            <?php if ( $saved ) : ?>
                <div class="notice notice-success is-dismissible">
                    <p><?php esc_html_e( 'MCP settings saved.', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                </div>
            <?php endif; ?>

            <form method="post">
                <?php wp_nonce_field( 'ai_agent_hub_mcp_save', 'ai_agent_hub_mcp_nonce' ); ?>
                <h2><?php esc_html_e( 'Server configuration', 'ai-workflow-automation-ai-agent-hub' ); ?></h2>
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row">
                            <label for="ai_agent_hub_server_id"><?php esc_html_e( 'Server ID', 'ai-workflow-automation-ai-agent-hub' ); ?></label>
                        </th>
                        <td>
                            <input name="server_id" id="ai_agent_hub_server_id" type="text" class="regular-text" value="<?php echo esc_attr( $settings['server_id'] ); ?>" />
                            <p class="description"><?php esc_html_e( 'Unique identifier visible to MCP clients.', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="ai_agent_hub_server_name"><?php esc_html_e( 'Server name', 'ai-workflow-automation-ai-agent-hub' ); ?></label>
                        </th>
                        <td>
                            <input name="name" id="ai_agent_hub_server_name" type="text" class="regular-text" value="<?php echo esc_attr( $settings['name'] ); ?>" />
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="ai_agent_hub_server_description"><?php esc_html_e( 'Description', 'ai-workflow-automation-ai-agent-hub' ); ?></label>
                        </th>
                        <td>
                            <textarea name="description" id="ai_agent_hub_server_description" class="large-text" rows="3"><?php echo esc_textarea( $settings['description'] ); ?></textarea>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="ai_agent_hub_namespace"><?php esc_html_e( 'REST namespace', 'ai-workflow-automation-ai-agent-hub' ); ?></label>
                        </th>
                        <td>
                            <input name="namespace" id="ai_agent_hub_namespace" type="text" class="regular-text" value="<?php echo esc_attr( $settings['namespace'] ); ?>" />
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="ai_agent_hub_route"><?php esc_html_e( 'REST route', 'ai-workflow-automation-ai-agent-hub' ); ?></label>
                        </th>
                        <td>
                            <input name="route" id="ai_agent_hub_route" type="text" class="regular-text" value="<?php echo esc_attr( $settings['route'] ); ?>" />
                            <p class="description"><?php echo esc_html( $http_url ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="ai_agent_hub_version"><?php esc_html_e( 'Version', 'ai-workflow-automation-ai-agent-hub' ); ?></label>
                        </th>
                        <td>
                            <input name="version" id="ai_agent_hub_version" type="text" class="regular-text" value="<?php echo esc_attr( $settings['version'] ); ?>" />
                        </td>
                    </tr>
                </table>

                <h2><?php esc_html_e( 'Expose abilities', 'ai-workflow-automation-ai-agent-hub' ); ?></h2>
                <p class="description"><?php esc_html_e( 'Select which abilities become MCP tools. Only abilities from enabled modules are listed.', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                <div class="ai-agent-hub-abilities-grid">
                    <?php if ( empty( $abilities ) ) : ?>
                        <p><?php esc_html_e( 'No abilities are available. Enable modules in Settings first.', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                    <?php else : ?>
                        <?php foreach ( $abilities as $ability ) : ?>
                            <?php $checked = in_array( $ability['id'], $settings['abilities'], true ) || empty( $settings['abilities'] ); ?>
                            <label class="ai-agent-hub-ability-card">
                                <input type="checkbox" name="abilities[]" value="<?php echo esc_attr( $ability['id'] ); ?>" <?php checked( $checked ); ?> />
                                <span class="ai-agent-hub-ability-title"><?php echo esc_html( $ability['label'] ); ?></span>
                                <span class="ai-agent-hub-ability-id"><?php echo esc_html( $ability['id'] ); ?></span>
                            </label>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>

                <h2><?php esc_html_e( 'Access control (optional OAuth-style token)', 'ai-workflow-automation-ai-agent-hub' ); ?></h2>
                <p class="description"><?php esc_html_e( 'Store OAuth client metadata for reference and optionally require a static bearer token for HTTP requests. Application Passwords continue to work out of the box.', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><label for="ai_agent_hub_oauth_client_id"><?php esc_html_e( 'Client ID', 'ai-workflow-automation-ai-agent-hub' ); ?></label></th>
                        <td>
                            <input name="oauth_client_id" id="ai_agent_hub_oauth_client_id" type="text" class="regular-text" value="<?php echo esc_attr( $settings['oauth']['client_id'] ?? '' ); ?>" />
                            <p class="description"><?php esc_html_e( 'Find this in your OAuth provider app settings.', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="ai_agent_hub_oauth_client_secret"><?php esc_html_e( 'Client secret', 'ai-workflow-automation-ai-agent-hub' ); ?></label></th>
                        <td>
                            <input name="oauth_client_secret" id="ai_agent_hub_oauth_client_secret" type="password" class="regular-text" value="<?php echo esc_attr( $settings['oauth']['client_secret'] ?? '' ); ?>" />
                            <p class="description"><?php esc_html_e( 'Keep this private; provided by your OAuth provider.', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="ai_agent_hub_oauth_auth_url"><?php esc_html_e( 'Authorization URL', 'ai-workflow-automation-ai-agent-hub' ); ?></label></th>
                        <td>
                            <input name="oauth_auth_url" id="ai_agent_hub_oauth_auth_url" type="url" class="regular-text" value="<?php echo esc_attr( $settings['oauth']['auth_url'] ?? '' ); ?>" />
                            <p class="description"><?php esc_html_e( 'Provider authorize endpoint, e.g. https://auth.example.com/oauth/authorize', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="ai_agent_hub_oauth_token_url"><?php esc_html_e( 'Token URL', 'ai-workflow-automation-ai-agent-hub' ); ?></label></th>
                        <td>
                            <input name="oauth_token_url" id="ai_agent_hub_oauth_token_url" type="url" class="regular-text" value="<?php echo esc_attr( $settings['oauth']['token_url'] ?? '' ); ?>" />
                            <p class="description"><?php esc_html_e( 'Provider token endpoint, e.g. https://auth.example.com/oauth/token', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="ai_agent_hub_oauth_redirect"><?php esc_html_e( 'Redirect URI', 'ai-workflow-automation-ai-agent-hub' ); ?></label></th>
                        <td>
                            <input name="oauth_redirect_uri" id="ai_agent_hub_oauth_redirect" type="url" class="regular-text" value="<?php echo esc_attr( $settings['oauth']['redirect_uri'] ?? '' ); ?>" />
                            <p class="description"><?php echo esc_html__( 'Register this callback at your provider; defaults to the MCP REST callback.', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row"><label for="ai_agent_hub_oauth_scopes"><?php esc_html_e( 'Scopes', 'ai-workflow-automation-ai-agent-hub' ); ?></label></th>
                        <td>
                            <input name="oauth_scopes" id="ai_agent_hub_oauth_scopes" type="text" class="regular-text" value="<?php echo esc_attr( $settings['oauth']['scopes'] ?? '' ); ?>" />
                            <p class="description"><?php esc_html_e( 'Space or comma separated, e.g. read write offline_access', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                        </td>
                    </tr>
                    <tr>
                    <th scope="row"><label for="ai_agent_hub_oauth_access_token"><?php esc_html_e( 'Static bearer token', 'ai-workflow-automation-ai-agent-hub' ); ?></label></th>
                    <td>
                        <input name="oauth_access_token" id="ai_agent_hub_oauth_access_token" type="text" class="regular-text" value="<?php echo esc_attr( $settings['oauth']['access_token'] ?? '' ); ?>" />
                        <p class="description"><?php esc_html_e( 'If set, HTTP requests must include Authorization: Bearer {token}. Leave blank to use standard WordPress auth.', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                    </td>
                </tr>
                <?php if ( ! empty( $settings['oauth']['access_token'] ) ) : ?>
                    <tr>
                        <th scope="row"><?php esc_html_e( 'Token status', 'ai-workflow-automation-ai-agent-hub' ); ?></th>
                        <td>
                            <p><?php echo esc_html__( 'Access token saved.', 'ai-workflow-automation-ai-agent-hub' ); ?></p>
                            <?php if ( ! empty( $settings['oauth']['expires_at'] ) ) : ?>
                                <p class="description">
                                    <?php
                                    /* translators: %s: expiration date */
                                    printf( esc_html__( 'Expires: %s', 'ai-workflow-automation-ai-agent-hub' ), esc_html( date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ), (int) $settings['oauth']['expires_at'] ) ) );
                                    ?>
                                </p>
                            <?php endif; ?>
                        </td>
                    </tr>
                <?php endif; ?>
            </table>

            <p class="submit">
                <button type="submit" class="button button-primary"><?php esc_html_e( 'Save MCP settings', 'ai-workflow-automation-ai-agent-hub' ); ?></button>
            </p>
        </form>

            <hr />
            <h2><?php esc_html_e( 'OAuth authorize', 'ai-workflow-automation-ai-agent-hub' ); ?></h2>
            <p class="description">
                <?php esc_html_e( 'Use this link to initiate an OAuth code grant with your provider. Tokens will be stored automatically on return.', 'ai-workflow-automation-ai-agent-hub' ); ?>
            </p>
            <?php if ( $authorize_url ) : ?>
                <p><a class="button button-secondary" href="<?php echo esc_url( $authorize_url ); ?>"><?php esc_html_e( 'Authorize now', 'ai-workflow-automation-ai-agent-hub' ); ?></a></p>
            <?php else : ?>
                <p class="description" style="color:#d63638;"><?php echo esc_html( $authorize_url_notice ); ?></p>
            <?php endif; ?>

            <hr />
            <h2><?php esc_html_e( 'Copy connection details', 'ai-workflow-automation-ai-agent-hub' ); ?></h2>
            <div class="ai-agent-hub-cards">
                <div class="card">
                    <h3><?php esc_html_e( 'HTTP endpoint', 'ai-workflow-automation-ai-agent-hub' ); ?></h3>
                    <code><?php echo esc_html( $http_url ); ?></code><br />
                    <button type="button" class="button ai-agent-hub-copy" data-copy="<?php echo esc_attr( $http_url ); ?>"><?php esc_html_e( 'Copy URL', 'ai-workflow-automation-ai-agent-hub' ); ?></button>
                </div>
                <div class="card">
                    <h3><?php esc_html_e( 'STDIO (WP-CLI)', 'ai-workflow-automation-ai-agent-hub' ); ?></h3>
                    <code><?php echo esc_html( $stdio_command ); ?></code><br />
                    <button type="button" class="button ai-agent-hub-copy" data-copy="<?php echo esc_attr( $stdio_command ); ?>"><?php esc_html_e( 'Copy command', 'ai-workflow-automation-ai-agent-hub' ); ?></button>
                </div>
                <div class="card">
                    <h3><?php esc_html_e( 'Remote proxy env (mcp-wordpress-remote)', 'ai-workflow-automation-ai-agent-hub' ); ?></h3>
                    <code>WP_API_URL=<?php echo esc_html( $remote_env['WP_API_URL'] ); ?></code><br />
                    <code>WP_API_USERNAME=<?php echo esc_html( $remote_env['WP_API_USERNAME'] ); ?></code><br />
                    <code>WP_API_PASSWORD=<?php echo esc_html( $remote_env['WP_API_PASSWORD'] ); ?></code><br />
                    <button type="button" class="button ai-agent-hub-copy" data-copy="<?php echo esc_attr( $remote_env_string ); ?>"><?php esc_html_e( 'Copy env sample', 'ai-workflow-automation-ai-agent-hub' ); ?></button>
                </div>
            </div>

            <div class="ai-agent-hub-help">
                <h2><?php esc_html_e( 'Client quick start', 'ai-workflow-automation-ai-agent-hub' ); ?></h2>
                <ol>
                    <li><?php esc_html_e( 'Ensure Composer dependencies are installed (wordpress/mcp-adapter + abilities-api) and abilities are registered.', 'ai-workflow-automation-ai-agent-hub' ); ?></li>
                    <li><?php esc_html_e( 'Copy the HTTP endpoint or STDIO command above.', 'ai-workflow-automation-ai-agent-hub' ); ?></li>
                    <li><?php esc_html_e( 'For Claude/ChatGPT desktop, paste into the MCP configuration (HTTP via mcp-wordpress-remote, or STDIO for local).', 'ai-workflow-automation-ai-agent-hub' ); ?></li>
                    <li><?php esc_html_e( 'If you set a static bearer token, include it as Authorization: Bearer {token}.', 'ai-workflow-automation-ai-agent-hub' ); ?></li>
                </ol>
            </div>
        </div>
        <script>
            document.addEventListener('click', function (event) {
                if (!event.target.classList.contains('ai-agent-hub-copy')) {
                    return;
                }
                var value = event.target.getAttribute('data-copy') || '';
                if (!value) {
                    return;
                }
                if (navigator.clipboard && navigator.clipboard.writeText) {
                    navigator.clipboard.writeText(value);
                } else {
                    var tempInput = document.createElement('textarea');
                    tempInput.value = value;
                    document.body.appendChild(tempInput);
                    tempInput.select();
                    document.execCommand('copy');
                    document.body.removeChild(tempInput);
                }
                var original = event.target.getAttribute('data-original-text') || event.target.textContent;
                event.target.setAttribute('data-original-text', original);
                event.target.textContent = '<?php echo esc_js( __( 'Copied', 'ai-workflow-automation-ai-agent-hub' ) ); ?>';
                setTimeout(function () {
                    event.target.textContent = original;
                }, 1500);
            });
        </script>
        <?php
    }

    private function handle_form_submission(): bool {
        if ( empty( $_POST['ai_agent_hub_mcp_nonce'] ) ) {
            return false;
        }

        if ( ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['ai_agent_hub_mcp_nonce'] ) ), 'ai_agent_hub_mcp_save' ) ) {
            return false;
        }

        $payload = [
            'server_id'   => sanitize_text_field( wp_unslash( $_POST['server_id'] ?? '' ) ),
            'name'        => sanitize_text_field( wp_unslash( $_POST['name'] ?? '' ) ),
            'description' => sanitize_text_field( wp_unslash( $_POST['description'] ?? '' ) ),
            'namespace'   => sanitize_text_field( wp_unslash( $_POST['namespace'] ?? '' ) ),
            'route'       => sanitize_text_field( wp_unslash( $_POST['route'] ?? '' ) ),
            'version'     => sanitize_text_field( wp_unslash( $_POST['version'] ?? AWFAH_VERSION ) ),
            'abilities'   => [],
            'oauth'       => [
                'client_id'     => sanitize_text_field( wp_unslash( $_POST['oauth_client_id'] ?? '' ) ),
                'client_secret' => sanitize_text_field( wp_unslash( $_POST['oauth_client_secret'] ?? '' ) ),
                'auth_url'      => sanitize_text_field( wp_unslash( $_POST['oauth_auth_url'] ?? '' ) ),
                'token_url'     => sanitize_text_field( wp_unslash( $_POST['oauth_token_url'] ?? '' ) ),
                'redirect_uri'  => sanitize_text_field( wp_unslash( $_POST['oauth_redirect_uri'] ?? '' ) ),
                'scopes'        => sanitize_text_field( wp_unslash( $_POST['oauth_scopes'] ?? '' ) ),
                'access_token'  => sanitize_text_field( wp_unslash( $_POST['oauth_access_token'] ?? '' ) ),
            ],
        ];

        if ( ! empty( $_POST['abilities'] ) && is_array( $_POST['abilities'] ) ) {
            $payload['abilities'] = array_values(
                array_unique(
                    array_map(
                        'sanitize_text_field',
                        wp_unslash( $_POST['abilities'] )
                    )
                )
            );
        }

        Plugin::update_mcp_settings( $payload );

        return true;
    }
}
