<?php

declare(strict_types=1);

require_once __DIR__ . '/../../vendor/autoload.php';

use App\Framework\Core\ContainerBootstrapper;
use App\Framework\Core\PathProvider;
use App\Framework\Mcp\McpServer;
use App\Framework\Mcp\McpToolRegistry;

echo "=== Git MCP Tools Test ===\n\n";

// Bootstrap container only (minimal setup for MCP tools)
$basePath = dirname(__DIR__, 2);
$pathProvider = new PathProvider($basePath);
$containerBootstrapper = new ContainerBootstrapper($pathProvider);
$container = $containerBootstrapper->boot();

// Get MCP Server
try {
    $mcpServer = $container->get(McpServer::class);
    $toolRegistry = $container->get(McpToolRegistry::class);

    echo "✓ MCP Server initialized\n\n";

    // Test 1: List all tools (including Git tools)
    echo "Test 1: List all MCP tools\n";
    echo str_repeat('-', 50) . "\n";

    $listToolsRequest = json_encode([
        'jsonrpc' => '2.0',
        'method' => 'tools/list',
        'id' => 1,
    ]);

    $response = $mcpServer->handleRequest($listToolsRequest);
    $result = json_decode($response, true);

    if (isset($result['result']['tools'])) {
        $allTools = $result['result']['tools'];
        $gitTools = array_filter($allTools, fn ($tool) => str_starts_with($tool['name'], 'git_'));

        echo "Total tools: " . count($allTools) . "\n";
        echo "Git tools: " . count($gitTools) . "\n\n";

        if (! empty($gitTools)) {
            echo "Available Git Tools:\n";
            foreach ($gitTools as $tool) {
                echo "  - {$tool['name']}: {$tool['description']}\n";
            }
        } else {
            echo "⚠ No Git tools found! Check GitToolsInitializer.\n";
        }
    } else {
        echo "✗ Failed to list tools\n";
        echo "Response: " . json_encode($result, JSON_PRETTY_PRINT) . "\n";
    }

    echo "\n";

    // Test 2: Call git_status tool
    echo "Test 2: Call git_status\n";
    echo str_repeat('-', 50) . "\n";

    $gitStatusRequest = json_encode([
        'jsonrpc' => '2.0',
        'method' => 'tools/call',
        'params' => [
            'name' => 'git_status',
            'arguments' => [],
        ],
        'id' => 2,
    ]);

    $response = $mcpServer->handleRequest($gitStatusRequest);
    $result = json_decode($response, true);

    if (isset($result['result'])) {
        $status = $result['result'];

        if (isset($status['content'][0]['text'])) {
            $statusData = json_decode($status['content'][0]['text'], true);

            if (isset($statusData['summary'])) {
                echo "Git Status Summary:\n";
                echo "  Staged: {$statusData['summary']['staged_count']}\n";
                echo "  Unstaged: {$statusData['summary']['unstaged_count']}\n";
                echo "  Untracked: {$statusData['summary']['untracked_count']}\n";
                echo "  Clean: " . ($statusData['clean'] ? 'Yes' : 'No') . "\n";

                if (! empty($statusData['staged'])) {
                    echo "\n  Staged files:\n";
                    foreach ($statusData['staged'] as $file) {
                        echo "    - {$file['file']} ({$file['status']})\n";
                    }
                }
            } else {
                echo "Status data: " . json_encode($statusData, JSON_PRETTY_PRINT) . "\n";
            }
        } else {
            echo "Result: " . json_encode($status, JSON_PRETTY_PRINT) . "\n";
        }
    } else {
        echo "✗ Failed to call git_status\n";
        echo "Response: " . json_encode($result, JSON_PRETTY_PRINT) . "\n";
    }

    echo "\n";

    // Test 3: Call git_branch_info
    echo "Test 3: Call git_branch_info\n";
    echo str_repeat('-', 50) . "\n";

    $branchInfoRequest = json_encode([
        'jsonrpc' => '2.0',
        'method' => 'tools/call',
        'params' => [
            'name' => 'git_branch_info',
            'arguments' => [],
        ],
        'id' => 3,
    ]);

    $response = $mcpServer->handleRequest($branchInfoRequest);
    $result = json_decode($response, true);

    if (isset($result['result']['content'][0]['text'])) {
        $branchData = json_decode($result['result']['content'][0]['text'], true);

        echo "Current branch: {$branchData['current_branch']}\n";
        echo "Local branches: {$branchData['total_local']}\n";
        echo "Remote branches: {$branchData['total_remote']}\n";

        if (! empty($branchData['local_branches'])) {
            echo "\nLocal branches:\n";
            foreach ($branchData['local_branches'] as $branch) {
                $marker = $branch === $branchData['current_branch'] ? '* ' : '  ';
                echo "{$marker}{$branch}\n";
            }
        }
    } else {
        echo "✗ Failed to get branch info\n";
        echo "Response: " . json_encode($result, JSON_PRETTY_PRINT) . "\n";
    }

    echo "\n";

    // Test 4: Call git_log
    echo "Test 4: Call git_log (last 5 commits)\n";
    echo str_repeat('-', 50) . "\n";

    $logRequest = json_encode([
        'jsonrpc' => '2.0',
        'method' => 'tools/call',
        'params' => [
            'name' => 'git_log',
            'arguments' => [
                'limit' => 5,
            ],
        ],
        'id' => 4,
    ]);

    $response = $mcpServer->handleRequest($logRequest);
    $result = json_decode($response, true);

    if (isset($result['result']['content'][0]['text'])) {
        $logData = json_decode($result['result']['content'][0]['text'], true);

        if (! empty($logData['commits'])) {
            echo "Recent commits:\n";
            foreach ($logData['commits'] as $commit) {
                echo "\n  {$commit['short_hash']} - {$commit['message']}\n";
                echo "  Author: {$commit['author']} <{$commit['email']}>\n";
                echo "  Date: {$commit['date']}\n";
            }
        }
    } else {
        echo "✗ Failed to get git log\n";
        echo "Response: " . json_encode($result, JSON_PRETTY_PRINT) . "\n";
    }

    echo "\n";

    // Test 5: Test git_generate_commit_message (if there are staged changes)
    echo "Test 5: Test git_generate_commit_message\n";
    echo str_repeat('-', 50) . "\n";

    $generateMsgRequest = json_encode([
        'jsonrpc' => '2.0',
        'method' => 'tools/call',
        'params' => [
            'name' => 'git_generate_commit_message',
            'arguments' => [],
        ],
        'id' => 5,
    ]);

    $response = $mcpServer->handleRequest($generateMsgRequest);
    $result = json_decode($response, true);

    if (isset($result['result']['content'][0]['text'])) {
        $msgData = json_decode($result['result']['content'][0]['text'], true);

        if (isset($msgData['suggested_message'])) {
            echo "Suggested commit message:\n";
            echo "  {$msgData['suggested_message']}\n\n";
            echo "Type: {$msgData['type']}\n";
            echo "Scope: " . ($msgData['scope'] ?? 'none') . "\n";
            echo "Description: {$msgData['description']}\n";

            if (isset($msgData['changes_summary'])) {
                echo "\nChanges summary:\n";
                echo "  Files: {$msgData['changes_summary']['file_count']}\n";
                echo "  Additions: {$msgData['changes_summary']['additions']}\n";
                echo "  Deletions: {$msgData['changes_summary']['deletions']}\n";
            }
        } elseif (isset($msgData['error'])) {
            echo "Note: {$msgData['error']}\n";
            if (isset($msgData['suggestion'])) {
                echo "Tip: {$msgData['suggestion']}\n";
            }
        }
    } else {
        echo "Response: " . json_encode($result, JSON_PRETTY_PRINT) . "\n";
    }

    echo "\n=== Test Complete ===\n";

} catch (\Throwable $e) {
    echo "✗ Error: {$e->getMessage()}\n";
    echo "File: {$e->getFile()}:{$e->getLine()}\n";
    echo "\nTrace:\n{$e->getTraceAsString()}\n";
}
