<?php

namespace App\Console\Commands\Extensions;

use App\Models\Extension;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;

class StatusCommand extends Command
{
    /**
     * The name and signature of the console command.
     */
    protected $signature = 'extension:status {id : The extension ID to check}';

    /**
     * The console command description.
     */
    protected $description = 'Show extension status';

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $extensionId = $this->argument('id');

        try {
            // Find extension
            $extension = Extension::where('extension_id', $extensionId)->first();

            if (!$extension) {
                $this->error("Extension '{$extensionId}' not found in database!");
                $this->newLine();

                // Check if extension exists in filesystem
                if ($this->extensionExistsInFilesystem($extensionId)) {
                    $this->info('Extension files found but not installed.');
                    $this->line("Run: php artisan extension:install {$extensionId}");
                } else {
                    $this->line('Run: php artisan extension:list --available to see available extensions');
                }

                return 1;
            }

            // Display status
            $this->newLine();
            $this->info("Extension Status: {$extension->name}");
            $this->newLine();

            $this->table(
                ['Property', 'Value'],
                [
                    ['ID', $extension->extension_id],
                    ['Name', $extension->name],
                    ['Version', $extension->version ?? 'N/A'],
                    ['Installed', $extension->installed ? '✓ Yes' : '✗ No'],
                    ['Enabled', $extension->enabled ? '✓ Yes' : '✗ No'],
                    ['Created', $extension->created_at->format('Y-m-d H:i:s')],
                    ['Updated', $extension->updated_at->format('Y-m-d H:i:s')],
                ]
            );

            $this->newLine();

            // Check and display requirements
            if ($this->extensionExistsInFilesystem($extensionId)) {
                $extensionClass = $this->findExtensionClass($extensionId);
                if ($extensionClass) {
                    // Get extension path
                    $extensionPath = $this->getExtensionPath($extensionId);

                    // Instantiate extension with path
                    $instance = new $extensionClass($extensionPath);

                    // Set extension context
                    $reflection = new \ReflectionClass($instance);
                    $property = $reflection->getProperty('extension');
                    $property->setAccessible(true);
                    $property->setValue($instance, $extension);

                    $requirementCheck = $instance->checkRequirements();

                    $this->info('Requirements Check:');
                    if (!empty($requirementCheck['errors'])) {
                        $this->error('  ❌ Errors:');
                        foreach ($requirementCheck['errors'] as $error) {
                            $this->line("    • {$error}");
                        }
                    }

                    if (!empty($requirementCheck['warnings'])) {
                        $this->warn('  ⚠️  Warnings:');
                        foreach ($requirementCheck['warnings'] as $warning) {
                            $this->line("    • {$warning}");
                        }
                    }

                    if ($requirementCheck['passed'] && empty($requirementCheck['warnings'])) {
                        $this->info('  ✓ All requirements met');
                    }

                    $this->newLine();
                }
            }

            // Show available actions
            $this->info('Available Actions:');
            if (!$extension->installed) {
                $this->line("  php artisan extension:install {$extensionId}");
            } elseif (!$extension->enabled) {
                $this->line("  php artisan extension:enable {$extensionId}");
            } else {
                $this->line("  php artisan extension:disable {$extensionId}");
            }

            return 0;

        } catch (\Exception $e) {
            $this->error('Failed to get status: ' . $e->getMessage());
            return 1;
        }
    }

    /**
     * Check if extension exists in filesystem.
     */
    protected function extensionExistsInFilesystem(string $extensionId): bool
    {
        // Convert kebab-case to StudlyCase
        $className = str_replace('-', '', ucwords($extensionId, '-'));
        $path = app_path("Extensions/Installed/{$className}/{$className}Extension.php");

        return File::exists($path);
    }

    /**
     * Find the extension class file.
     */
    protected function findExtensionClass(string $extensionId): ?string
    {
        // Convert kebab-case to StudlyCase (e.g., live-chat -> LiveChat)
        $className = str_replace('-', '', ucwords($extensionId, '-'));

        $path = app_path("Extensions/Installed/{$className}/{$className}Extension.php");

        if (!File::exists($path)) {
            return null;
        }

        $class = "App\\Extensions\\Installed\\{$className}\\{$className}Extension";

        if (!class_exists($class)) {
            return null;
        }

        return $class;
    }

    /**
     * Get the extension directory path.
     */
    protected function getExtensionPath(string $extensionId): string
    {
        // Convert kebab-case to StudlyCase (e.g., live-chat -> LiveChat)
        $className = str_replace('-', '', ucwords($extensionId, '-'));
        return app_path("Extensions/Installed/{$className}");
    }
}
