<?php

namespace PortalPeople\mcp\controllers;

use Yii;
use yii\helpers\Html;
use yii\web\Controller;
use yii\web\Response;

class ConfigController extends Controller
{
    public function actionSetup()
    {
        $hostInfo = rtrim((string)Yii::$app->request->hostInfo, '/');
        $baseUrl = rtrim((string)Yii::$app->request->baseUrl, '/');
        $endpoint = $hostInfo . $baseUrl . '/mcp/rpc';

        $module = Yii::$app->getModule('mcp');
        $moduleBasePath = $module ? $module->basePath : dirname(__DIR__);
        $bridgePath = realpath($moduleBasePath . '/../bin/mcp-http-bridge.php');
        $bridgePath = $bridgePath ?: ($moduleBasePath . '/../bin/mcp-http-bridge.php');

        $claudeConfig = [
            'mcpServers' => [
                'ngauge-mcp' => [
                    'command' => 'php',
                    'args' => [
                        $bridgePath,
                        '--endpoint=' . $endpoint,
                    ],
                    'env' => [
                        'MCP_ACCESS_TOKEN' => '<paste-access-token>',
                    ],
                ],
            ],
        ];

        $vscodeConfig = [
            'servers' => [
                'ngauge-mcp' => [
                    'type' => 'stdio',
                    'command' => 'php',
                    'args' => [
                        $bridgePath,
                        '--endpoint=' . $endpoint,
                    ],
                    'env' => [
                        'MCP_ACCESS_TOKEN' => '<paste-access-token>',
                    ],
                ],
            ],
        ];

        if (Yii::$app->request->get('format') === 'json') {
            Yii::$app->response->format = Response::FORMAT_JSON;

            return [
                'endpoint' => $endpoint,
                'bridgePath' => $bridgePath,
                'claudeConfig' => $claudeConfig,
                'vscodeConfig' => $vscodeConfig,
            ];
        }

        Yii::$app->response->format = Response::FORMAT_HTML;

        $claudeJson = json_encode($claudeConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);
        $vscodeJson = json_encode($vscodeConfig, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

        return '<h1>NGauge MCP Setup</h1>'
            . '<p><strong>Detected endpoint:</strong> ' . Html::encode($endpoint) . '</p>'
            . '<p><strong>Bridge script:</strong> ' . Html::encode($bridgePath) . '</p>'
            . '<h2>Claude Desktop (claude_desktop_config.json)</h2>'
            . '<pre>' . Html::encode((string)$claudeJson) . '</pre>'
            . '<h2>VS Code (.vscode/mcp.json)</h2>'
            . '<pre>' . Html::encode((string)$vscodeJson) . '</pre>'
            . '<p>Add a real token value for <code>MCP_ACCESS_TOKEN</code>. You can generate one via the MCP tool <code>create_mcp_token</code>.</p>'
            . '<p>For machine-readable output, use <code>?format=json</code>.</p>';
    }
}
