<?php

namespace App\Console\Commands;

use App\Services\Installation\SystemHealthService;
use Illuminate\Console\Command;

class TicagaHealth extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'ticaga:health
                            {--json : Output results as JSON}
                            {--detailed : Show detailed information}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check Ticaga system health and diagnose issues';

    protected SystemHealthService $health;

    public function __construct(SystemHealthService $health)
    {
        parent::__construct();
        $this->health = $health;
    }

    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $summary = $this->health->getHealthSummary();

        // JSON output
        if ($this->option('json')) {
            $this->line(json_encode($summary, JSON_PRETTY_PRINT));

            return $summary['status'] === 'ok' ? self::SUCCESS : self::FAILURE;
        }

        // Human-readable output
        $this->displayHeader($summary);
        $this->displayOverallStatus($summary);

        if (count($summary['issues']) > 0) {
            $this->displayIssues($summary['issues']);
        }

        if (count($summary['warnings']) > 0) {
            $this->displayWarnings($summary['warnings']);
        }

        // Display upgrade alert if available
        if ($summary['upgrade']['upgrade_available'] ?? false) {
            $this->displayUpgradeAlert($summary['upgrade']);
        }

        if ($this->option('detailed')) {
            $this->displayDetailedChecks($summary['checks']);
        } else {
            $this->newLine();
            $this->info('Run with --detailed to see detailed system checks');
        }

        $this->newLine();

        return $summary['status'] === 'ok' ? self::SUCCESS : self::FAILURE;
    }

    protected function displayHeader(array $summary): void
    {
        $this->newLine();
        $this->info('╔════════════════════════════════════════════╗');
        $this->info('║      Ticaga System Health Check            ║');

        if ($summary['installed']) {
            $version = str_pad('Version ' . ($summary['version'] ?? 'Unknown'), 38);
            $this->info('║      ' . $version . '    ║');
        }

        $this->info('╚════════════════════════════════════════════╝');
        $this->newLine();
    }

    protected function displayOverallStatus(array $summary): void
    {
        $status = $summary['status'];

        if ($status === 'ok') {
            $this->info('Overall Status: ✓ HEALTHY');
            $this->info('All systems are operational');
        } elseif ($status === 'warning') {
            $this->warn('Overall Status: ⚠ WARNING');
            $this->warn('Some issues detected but system is functional');
        } else {
            $this->error('Overall Status: ✗ CRITICAL');
            $this->error('Critical issues require immediate attention');
        }

        $this->newLine();
    }

    protected function displayIssues(array $issues): void
    {
        $this->error('CRITICAL ISSUES:');

        foreach ($issues as $issue) {
            $this->error('  ✗ ' . $issue);
        }

        $this->newLine();
    }

    protected function displayWarnings(array $warnings): void
    {
        $this->warn('WARNINGS:');

        foreach ($warnings as $warning) {
            $this->warn('  ⚠ ' . $warning);
        }

        $this->newLine();
    }

    protected function displayDetailedChecks(array $checks): void
    {
        $this->newLine();
        $this->info('═══════════════════════════════════════════');
        $this->info('DETAILED SYSTEM CHECKS');
        $this->info('═══════════════════════════════════════════');

        // Files Check
        $this->newLine();
        $this->displayFilesCheck($checks['files']);

        // Database Check
        $this->newLine();
        $this->displayDatabaseCheck($checks['database']);

        // Services Check
        $this->newLine();
        $this->displayServicesCheck($checks['services']);

        // Permissions Check
        $this->newLine();
        $this->displayPermissionsCheck($checks['permissions']);

        // Dependencies Check
        $this->newLine();
        $this->displayDependenciesCheck($checks['dependencies']);

        // Extensions Check
        $this->newLine();
        $this->displayExtensionsCheck($checks['extensions']);
    }

    protected function displayFilesCheck(array $files): void
    {
        $this->info('Core Files:');

        if ($files['status'] === 'ok') {
            $this->info('  ✓ All required files present (' . $files['present'] . '/' . $files['total'] . ')');
        } else {
            $this->warn('  ⚠ Missing files: ' . $files['missing'] . '/' . $files['total']);

            if (count($files['missing_files']) > 0) {
                $this->warn('     Missing:');

                foreach ($files['missing_files'] as $file) {
                    $this->warn('       - ' . $file);
                }
            }
        }
    }

    protected function displayDatabaseCheck(array $database): void
    {
        $this->info('Database:');

        if ($database['connected']) {
            $this->info('  ✓ Connected');

            if ($database['has_users']) {
                $this->info('  ✓ Users table populated');
            } else {
                $this->warn('  ⚠ Users table is empty');
            }

            if ($database['pending_migrations'] > 0) {
                $this->warn('  ⚠ Pending migrations: ' . $database['pending_migrations']);

                if (count($database['pending_migration_list']) > 0) {
                    $maxShow = 5;
                    $migrations = array_slice($database['pending_migration_list'], 0, $maxShow);

                    foreach ($migrations as $migration) {
                        $this->warn('     - ' . $migration);
                    }

                    if (count($database['pending_migration_list']) > $maxShow) {
                        $remaining = count($database['pending_migration_list']) - $maxShow;
                        $this->warn('     ... and ' . $remaining . ' more');
                    }

                    $this->newLine();
                    $this->info('  Run "php artisan migrate" to apply pending migrations');
                }
            } else {
                $this->info('  ✓ All migrations applied');
            }
        } else {
            $this->error('  ✗ Connection failed');

            if ($database['error']) {
                $this->error('     ' . $database['error']);
            }
        }
    }

    protected function displayServicesCheck(array $services): void
    {
        $this->info('Services:');

        foreach ($services['services'] as $service => $running) {
            $serviceName = ucwords(str_replace('_', ' ', $service));

            if ($running) {
                $this->info('  ✓ ' . $serviceName . ' is running');
            } else {
                $this->error('  ✗ ' . $serviceName . ' is not running');

                if ($service === 'mysql') {
                    $this->info('     Start with: sudo systemctl start mysqld');
                }
            }
        }
    }

    protected function displayPermissionsCheck(array $permissions): void
    {
        $this->info('Permissions:');

        foreach ($permissions['directories'] as $name => $data) {
            if ($data['writable']) {
                $this->info('  ✓ ' . $name . ' is writable');
            } else {
                $this->error('  ✗ ' . $name . ' is not writable');
                $this->error('     Path: ' . $data['path']);
                $this->info('     Fix with: sudo chmod -R 775 ' . $data['path']);
                $this->info('               sudo chown -R apache:apache ' . $data['path']);
            }
        }
    }

    protected function displayDependenciesCheck(array $dependencies): void
    {
        $this->info('Dependencies:');

        if ($dependencies['composer']) {
            $this->info('  ✓ Composer dependencies installed');
        } else {
            $this->error('  ✗ Composer dependencies missing');
            $this->info('     Install with: composer install');
        }

        if ($dependencies['npm']) {
            $this->info('  ✓ NPM dependencies installed');
        } else {
            $this->warn('  ⚠ NPM dependencies missing');
            $this->info('     Install with: npm install');
        }
    }

    protected function displayExtensionsCheck(array $extensions): void
    {
        $this->info('Extensions:');

        if ($extensions['status'] === 'ok') {
            $count = $extensions['installed'] ?? 0;
            $this->info('  ✓ Extension system working (' . $count . ' installed)');
        } elseif ($extensions['status'] === 'pending') {
            $this->warn('  ⚠ ' . ($extensions['message'] ?? 'Extension check pending'));
        } else {
            $this->error('  ✗ Extension system error');

            if (isset($extensions['error'])) {
                $this->error('     ' . $extensions['error']);
            }
        }
    }

    protected function displayUpgradeAlert(array $upgrade): void
    {
        $this->newLine();
        $this->warn('═══════════════════════════════════════════');
        $this->warn('UPGRADE AVAILABLE');
        $this->warn('═══════════════════════════════════════════');
        $this->newLine();
        $this->warn('  Current Version: ' . $upgrade['installed_version']);
        $this->info('  New Version:     ' . $upgrade['config_version']);
        $this->newLine();
        $this->info('  To upgrade:');
        $this->info('  1. Backup your database');
        $this->info('  2. Run: php artisan migrate --force');
        $this->info('  3. Run: php artisan ticaga:health --detailed');
        $this->newLine();
    }
}
