<?php

namespace App\Console\Commands;

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

class ImportFoodsFromMarkdown extends Command
{
    protected $signature = 'foods:import-md {file? : Path to markdown file}';
    protected $description = 'Import foods from a markdown file (one food per line)';

    public function handle()
    {
        $filePath = $this->argument('file') ?? base_path('docs/alimentos.md');

        if (!File::exists($filePath)) {
            $this->error("File not found: {$filePath}");
            return 1;
        }

        $content = File::get($filePath);
        
        // Handle different line endings
        $content = str_replace(["\r\n", "\r"], "\n", $content);
        $lines = array_filter(array_map('trim', explode("\n", $content)), function($line) {
            return !empty($line);
        });

        $imported = 0;
        $skipped = 0;
        $errors = [];

        $this->info("Importing foods from: {$filePath}");
        $this->info("Found " . count($lines) . " lines to process...\n");

        $bar = $this->output->createProgressBar(count($lines));
        $bar->start();

        foreach ($lines as $line) {
            // Skip empty lines and headers
            if (empty($line) || str_starts_with($line, '#') || str_starts_with($line, '---')) {
                $bar->advance();
                continue;
            }

            $foodName = trim($line);
            
            // Check if food already exists (case-insensitive)
            $exists = Food::whereRaw('LOWER(name) = ?', [strtolower($foodName)])->exists();
            
            if ($exists) {
                $skipped++;
                $bar->advance();
                continue;
            }

            try {
                // Create food with default values (macros at 0, to be updated later)
                Food::create([
                    'name' => $foodName,
                    'category' => $this->guessCategory($foodName),
                    'proteins' => 0,
                    'carbs' => 0,
                    'fats' => 0,
                    'calories' => 0,
                    'fiber' => 0,
                    'serving_size' => '100g',
                    'serving_weight' => 100,
                    'is_custom' => false,
                    'is_active' => true,
                    'user_id' => null,
                ]);
                $imported++;
            } catch (\Exception $e) {
                $errors[] = "{$foodName}: {$e->getMessage()}";
            }

            $bar->advance();
        }

        $bar->finish();
        $this->newLine(2);

        $this->info("✅ Import completed!");
        $this->info("   Imported: {$imported}");
        $this->info("   Skipped (already exist): {$skipped}");
        
        if (count($errors) > 0) {
            $this->warn("   Errors: " . count($errors));
            foreach (array_slice($errors, 0, 5) as $error) {
                $this->error("   - {$error}");
            }
        }

        return 0;
    }

    /**
     * Guess the category based on food name.
     */
    private function guessCategory(string $name): ?string
    {
        $name = strtolower($name);

        // Proteins
        $proteins = ['pollo', 'pavo', 'res', 'cerdo', 'pescado', 'tilapia', 'salmon', 'atún', 'tuna', 
                     'huevo', 'clara', 'carne', 'bacon', 'tocino', 'jamón', 'camarones', 'langosta',
                     'sardina', 'bacalao', 'mero', 'churrasco', 'proteína', 'whey', 'hígado'];
        foreach ($proteins as $p) {
            if (str_contains($name, $p)) return 'Proteínas';
        }

        // Carbs
        $carbs = ['arroz', 'pasta', 'pan', 'tortilla', 'avena', 'quinoa', 'papa', 'batata', 
                  'yuca', 'plátano', 'cereal', 'galleta', 'bagel', 'maíz', 'trigo', 'harina'];
        foreach ($carbs as $c) {
            if (str_contains($name, $c)) return 'Carbohidratos';
        }

        // Fruits
        $fruits = ['manzana', 'banana', 'piña', 'fresa', 'naranja', 'mandarina', 'melón', 
                   'sandía', 'kiwi', 'uva', 'pera', 'guayaba', 'lechosa', 'papaya', 'fruta'];
        foreach ($fruits as $f) {
            if (str_contains($name, $f)) return 'Frutas';
        }

        // Fats
        $fats = ['aceite', 'mantequilla', 'aguacate', 'almendra', 'nuez', 'semilla', 
                 'pistacho', 'cajú', 'coco', 'manteca', 'queso'];
        foreach ($fats as $f) {
            if (str_contains($name, $f)) return 'Grasas';
        }

        // Dairy
        $dairy = ['yogurt', 'leche', 'kéfir', 'ricotta', 'cottage', 'crema'];
        foreach ($dairy as $d) {
            if (str_contains($name, $d)) return 'Lácteos';
        }

        // Vegetables
        $veggies = ['vegetal', 'verde', 'tomate', 'pepino', 'apio', 'zanahoria', 'champiñón', 'lechuga'];
        foreach ($veggies as $v) {
            if (str_contains($name, $v)) return 'Vegetales';
        }

        // Legumes
        $legumes = ['habichuela', 'lenteja', 'garbanzo', 'frijol', 'guandul'];
        foreach ($legumes as $l) {
            if (str_contains($name, $l)) return 'Legumbres';
        }

        // Supplements
        $supps = ['bcaa', 'eaa', 'creatina', 'proteína', 'suplemento'];
        foreach ($supps as $s) {
            if (str_contains($name, $s)) return 'Suplementos';
        }

        return null;
    }
}
