<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Symfony\Component\Process\Process;

class RunNcdAnalysis extends Command
{
    protected $signature = 'ncd:analyze
        {--config= : Path to config.yaml}
        {--views= : Path to metrics_views.sql}
        {--python= : Python interpreter path}
        {--timeout=0 : Timeout in seconds (0 disables)}
        {--dry-run : Print command without running}';

    protected $description = 'Run the NCD analytics pipeline via Python using Laravel database credentials';

    public function handle(): int
    {
        $basePath = base_path();
        $configPath = $this->option('config') ?: base_path('config.yaml');
        $viewsPath = $this->option('views') ?: base_path('metrics_views.sql');
        $pythonPath = $this->option('python') ?: $this->defaultPythonPath();

        $command = [
            $pythonPath,
            base_path('ncd_analysis.py'),
            '--config',
            $configPath,
            '--views',
            $viewsPath,
        ];

        $this->info('Running NCD analytics...');
        $this->line('Command: ' . implode(' ', array_map('escapeshellarg', $command)));

        if ($this->option('dry-run')) {
            $this->warn('Dry run enabled; command not executed.');
            return Command::SUCCESS;
        }

        $process = new Process($command, $basePath, $this->buildEnv());
        $timeout = (int) $this->option('timeout');
        if ($timeout > 0) {
            $process->setTimeout($timeout);
        } else {
            $process->setTimeout(null);
        }

        $process->run(function ($type, $buffer) {
            $this->output->write($buffer);
        });

        if (!$process->isSuccessful()) {
            $this->error('NCD analytics failed with exit code ' . $process->getExitCode());
            return Command::FAILURE;
        }

        $this->info('NCD analytics completed successfully.');
        return Command::SUCCESS;
    }

    private function defaultPythonPath(): string
    {
        $venvPython = base_path('.venv/bin/python');
        if (file_exists($venvPython)) {
            return $venvPython;
        }
        return 'python3';
    }

    private function buildEnv(): array
    {
        $mysql = config('database.connections.mysql', []);
        $overrides = array_filter([
            'DB_HOST' => $mysql['host'] ?? null,
            'DB_PORT' => isset($mysql['port']) ? (string) $mysql['port'] : null,
            'DB_USERNAME' => $mysql['username'] ?? null,
            'DB_PASSWORD' => $mysql['password'] ?? null,
            'NCD_LARAVEL_PATH' => base_path(),
            'PYTHONUNBUFFERED' => '1',
        ], static function ($value) {
            return $value !== null;
        });

        return array_merge($_SERVER ?? [], $_ENV ?? [], $overrides);
    }
}
