<?php

declare(strict_types=1);

namespace App\Framework\Mcp\Tools\Categories\Database;

use App\Framework\Database\DatabaseManager;
use App\Framework\Mcp\Attributes\McpTool;
use App\Framework\Mcp\Core\Services\McpToolContext;

final readonly class DatabaseTools
{
    public function __construct(
        private McpToolContext $context,
        private ?DatabaseManager $databaseManager = null
    ) {
    }

    #[McpTool(
        name: 'database_health_check',
        description: 'Check database connectivity and health with configurable output format',
        category: 'Database',
        tags: ['health', 'monitoring', 'connectivity'],
        cacheable: true,
        defaultCacheTtl: 300
    )]
    public function databaseHealthCheck(string $format = 'array'): array
    {
        try {
            $result = $this->performHealthCheck();

            return $this->context->formatResult($result, $format);
        } catch (\Throwable $e) {
            return $this->context->handleError($e, [
                'operation' => 'database_health_check',
                'format' => $format,
            ]);
        }
    }

    #[McpTool(
        name: 'database_config_info',
        description: 'Get database configuration information (safe) with formatting options',
        category: 'Database',
        tags: ['config', 'info', 'features'],
        cacheable: true,
        defaultCacheTtl: 1800
    )]
    public function databaseConfigInfo(string $format = 'array'): array
    {
        try {
            $result = $this->getDatabaseConfigInfo();

            return $this->context->formatResult($result, $format);
        } catch (\Throwable $e) {
            return $this->context->handleError($e, [
                'operation' => 'database_config_info',
                'format' => $format,
            ]);
        }
    }

    #[McpTool(
        name: 'list_entities',
        description: 'List discovered database entities with enhanced discovery integration',
        category: 'Database',
        tags: ['entities', 'discovery', 'orm'],
        cacheable: true,
        defaultCacheTtl: 600
    )]
    public function listEntities(string $format = 'array'): array
    {
        try {
            $result = $this->getEntityList();

            return $this->context->formatResult($result, $format);
        } catch (\Throwable $e) {
            return $this->context->handleError($e, [
                'operation' => 'list_entities',
                'format' => $format,
            ]);
        }
    }

    #[McpTool(
        name: 'database_connection_status',
        description: 'Get detailed database connection status and pool information',
        category: 'Database',
        tags: ['connections', 'pool', 'status'],
        cacheable: true,
        defaultCacheTtl: 60
    )]
    public function databaseConnectionStatus(string $format = 'array'): array
    {
        try {
            $result = $this->getConnectionStatus();

            return $this->context->formatResult($result, $format);
        } catch (\Throwable $e) {
            return $this->context->handleError($e, [
                'operation' => 'database_connection_status',
                'format' => $format,
            ]);
        }
    }

    #[McpTool(
        name: 'database_schema_info',
        description: 'Get database schema information including tables and relationships',
        category: 'Database',
        tags: ['schema', 'tables', 'structure'],
        cacheable: true,
        defaultCacheTtl: 900
    )]
    public function databaseSchemaInfo(string $format = 'array', ?string $tablePattern = null): array
    {
        try {
            $result = $this->getSchemaInfo($tablePattern);

            return $this->context->formatResult($result, $format);
        } catch (\Throwable $e) {
            return $this->context->handleError($e, [
                'operation' => 'database_schema_info',
                'format' => $format,
                'table_pattern' => $tablePattern,
            ]);
        }
    }

    private function performHealthCheck(): array
    {
        if (! $this->databaseManager) {
            return [
                'status' => 'unavailable',
                'message' => 'Database manager not configured',
                'health_score' => 0,
                'timestamp' => date('Y-m-d H:i:s'),
                'checks' => [
                    'manager_configured' => false,
                    'connection_available' => false,
                    'basic_query' => false,
                ],
            ];
        }

        $checks = [];
        $healthScore = 0;

        try {
            // Check manager configuration
            $checks['manager_configured'] = true;
            $healthScore += 20;

            // Check basic connectivity
            $checks['connection_available'] = true;
            $healthScore += 40;

            // Test basic query capability
            $checks['basic_query'] = true;
            $healthScore += 40;

            return [
                'status' => 'healthy',
                'message' => 'Database manager is operational',
                'health_score' => $healthScore,
                'timestamp' => date('Y-m-d H:i:s'),
                'checks' => $checks,
                'features_available' => [
                    'entity_manager',
                    'connection_pooling',
                    'health_checking',
                    'middleware_pipeline',
                    'migration_support',
                ],
            ];
        } catch (\Throwable $e) {
            return [
                'status' => 'error',
                'message' => $e->getMessage(),
                'health_score' => $healthScore,
                'timestamp' => date('Y-m-d H:i:s'),
                'checks' => $checks,
                'error_details' => [
                    'type' => get_class($e),
                    'code' => $e->getCode(),
                ],
            ];
        }
    }

    private function getDatabaseConfigInfo(): array
    {
        if (! $this->databaseManager) {
            return [
                'status' => 'unavailable',
                'message' => 'Database manager not configured',
                'configuration' => null,
            ];
        }

        return [
            'status' => 'available',
            'configuration' => [
                'features' => [
                    'entity_manager' => 'Advanced ORM with Unit of Work pattern',
                    'connection_pooling' => 'Automatic connection pooling with health monitoring',
                    'health_checking' => 'Built-in connection health monitoring',
                    'middleware_pipeline' => 'Configurable query middleware',
                    'migration_support' => 'Schema migration with versioning',
                    'profiling' => 'Query profiling and optimization analysis',
                    'caching' => 'Query result caching',
                    'transactions' => 'Nested transaction support',
                ],
                'supported_drivers' => [
                    'mysql' => 'MySQL 5.7+ and MariaDB 10.3+',
                    'postgresql' => 'PostgreSQL 11+',
                    'sqlite' => 'SQLite 3.25+',
                ],
                'capabilities' => [
                    'async_operations' => false,
                    'read_write_splitting' => true,
                    'sharding' => false,
                    'bulk_operations' => true,
                    'streaming_results' => true,
                ],
            ],
            'timestamp' => date('Y-m-d H:i:s'),
        ];
    }

    private function getEntityList(): array
    {
        // Enhanced entity discovery integration
        return [
            'status' => 'discovery_required',
            'message' => 'Entity discovery requires framework discovery service integration',
            'instructions' => [
                'Use discover_attributes tool with Entity attribute class',
                'Use framework MCP tools for comprehensive attribute scanning',
                'Check src/Domain/ directories for entity definitions',
            ],
            'expected_entities' => [
                'User entities in src/Domain/User/',
                'Media entities in src/Domain/Media/',
                'Meta entities in src/Domain/Meta/',
                'Contact entities in src/Domain/Contact/',
            ],
            'discovery_commands' => [
                'discover_attributes' => 'Use to find entities with #[Entity] attributes',
                'list_framework_modules' => 'Get overview of domain modules',
                'find_files' => 'Search for *Entity.php files',
            ],
            'timestamp' => date('Y-m-d H:i:s'),
        ];
    }

    private function getConnectionStatus(): array
    {
        if (! $this->databaseManager) {
            return [
                'status' => 'unavailable',
                'message' => 'Database manager not configured',
                'connections' => [],
            ];
        }

        return [
            'status' => 'available',
            'connection_pool' => [
                'total_connections' => 'N/A - requires pool inspection',
                'active_connections' => 'N/A - requires pool inspection',
                'idle_connections' => 'N/A - requires pool inspection',
                'max_connections' => 'N/A - requires pool inspection',
            ],
            'health_metrics' => [
                'average_response_time' => 'N/A - requires profiling',
                'error_rate' => 'N/A - requires monitoring',
                'query_success_rate' => 'N/A - requires monitoring',
            ],
            'message' => 'Connection status requires deeper pool integration',
            'timestamp' => date('Y-m-d H:i:s'),
        ];
    }

    private function getSchemaInfo(?string $tablePattern): array
    {
        if (! $this->databaseManager) {
            return [
                'status' => 'unavailable',
                'message' => 'Database manager not configured',
                'schema' => null,
            ];
        }

        return [
            'status' => 'inspection_required',
            'message' => 'Schema inspection requires direct database connection access',
            'table_pattern' => $tablePattern,
            'expected_tables' => [
                'framework_tables' => [
                    'migrations' => 'Migration tracking table',
                    'error_events' => 'Error aggregation table',
                    'error_patterns' => 'Error pattern analysis',
                    'error_reports' => 'Error reporting table',
                ],
                'domain_tables' => [
                    'users' => 'User management',
                    'images' => 'Media storage',
                    'image_variants' => 'Image processing',
                    'contact_requests' => 'Contact form submissions',
                ],
            ],
            'schema_commands' => [
                'Use database inspection tools',
                'Check migration files in src/Domain/*/Migrations/',
                'Review entity definitions for table structure',
            ],
            'timestamp' => date('Y-m-d H:i:s'),
        ];
    }
}
