<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use App\Services\Ads\MajidApiClient;
use App\Services\Ads\Normalizer;
use App\Services\Ads\OpportunityScorer;
use App\Services\Ads\Deduper;
use Illuminate\Support\Facades\DB;

class TestAdsSystem extends Command
{
    protected $signature = 'ads:test-system {--source=bama} {--query=206} {--debug-normalization} {--test-real-data} {--test-cities}';
    protected $description = 'Test the ads system with a simple query';

    public function handle()
    {
        $source = $this->option('source');
        $query = $this->option('query');
        $debugNormalization = $this->option('debug-normalization');
        $testRealData = $this->option('test-real-data');
        $testCities = $this->option('test-cities');

        $this->info("🧪 Testing ads system with source: {$source}, query: {$query}");

        if ($debugNormalization) {
            $this->debugNormalization();
            return 0;
        }

        if ($testRealData) {
            $this->testWithRealData();
            return 0;
        }

        if ($testCities) {
            $this->testCityMapping();
            return 0;
        }

        try {
            // Test API client
            $this->info("1. Testing API client...");
            $client = app(MajidApiClient::class);

            if ($source === 'bama') {
                $data = $client->bamaSearch($query, 1);
            } else {
                $data = $client->divarScrape("https://divar.ir/s/tehran/car?q=" . urlencode($query));
            }

            if (empty($data)) {
                $this->warn("   ⚠️ No data returned from API");
                return 1;
            }

            $this->info("   ✅ API returned " . count($data) . " items");

            // Test normalization
            $this->info("2. Testing normalization...");
            $normalizer = new Normalizer();
            $scorer = new OpportunityScorer();
            $deduper = new Deduper();

            $normalizedCount = 0;
            $scoredCount = 0;

            foreach (array_slice($data, 0, 3) as $item) {
                // Handle different item types
                if (is_string($item)) {
                    // For Divar HTML strings, create array structure
                    $item = [
                        'title' => $item,
                        'source' => $source,
                        'link' => 'https://divar.ir/test',
                        'price' => '500000000',
                        'mileage' => '50000',
                        'year' => '1398'
                    ];
                } elseif (is_array($item) || is_object($item)) {
                    $item = (array)$item;
                    $item['source'] = $source;
                } else {
                    continue; // Skip invalid items
                }

                $normalized = $normalizer->normalize($item);

                if (!empty($normalized['code'])) {
                    $normalizedCount++;

                    // Test scoring
                    $score = $scorer->score(
                        $normalized['price'],
                        100, // mock median
                        25,  // mock sample count
                        $normalized['km'],
                        $normalized['year']
                    );

                    if ($score['score'] > 0) {
                        $scoredCount++;
                    }

                    $this->line("   📊 Item: {$normalized['brand']} {$normalized['model']} - Score: {$score['score']}");
                }
            }

            $this->info("   ✅ Normalized: {$normalizedCount}, Scored: {$scoredCount}");

            // Test database operations
            $this->info("3. Testing database operations...");

            // Check if tables exist
            $tables = ['ads_raw', 'opportunities', 'cities'];
            foreach ($tables as $table) {
                if (DB::getSchemaBuilder()->hasTable($table)) {
                    $this->info("   ✅ Table {$table} exists");
                } else {
                    $this->warn("   ⚠️ Table {$table} missing - run migrations");
                }
            }

            $this->info("🎉 Ads system test completed successfully!");
        return 0;

        } catch (\Throwable $e) {
            $this->error("❌ Test failed: " . $e->getMessage());
            $this->error("   File: " . $e->getFile() . ":" . $e->getLine());
            return 1;
        }
    }

    private function debugNormalization()
    {
        $this->info("🔍 Debug Normalization Mode");
        $this->info("Testing with real data samples...");

        $normalizer = new Normalizer();

        // Sample data from real Divar API response
        $divarSamples = [
            [
                'source' => 'divar',
                'title' => 'پژو ۲۰۶ تیپ ۵ مدل ۱۳۹۸',
                'brand' => 'peugeot',
                'model' => '۲۰۶',
                'trim' => 'تیپ ۵',
                'year' => '۱۳۹۸',
                'price' => '۵۶۰,۰۰۰,۰۰۰ تومان',
                'mileage' => '۴۵,۰۰۰',
                'location' => 'تهران',
                'link' => '/v/peugeot-206-1398',
                'body_status' => 'سالم'
            ],
            [
                'source' => 'divar',
                'title' => 'تیبا SX مدل ۱۴۰۰',
                'brand' => 'tiba',
                'model' => 'SX',
                'trim' => null,
                'year' => '۱۴۰۰',
                'price' => '۳۸۵,۰۰۰,۰۰۰ تومان',
                'mileage' => '۲۵,۰۰۰',
                'location' => 'اصفهان',
                'link' => '/v/tiba-sx-1400',
                'body_status' => 'خوب'
            ],
            [
                'source' => 'divar',
                'title' => 'کوییک R پلاس مدل ۱۴۰۱',
                'brand' => 'quick',
                'model' => 'R پلاس',
                'trim' => null,
                'year' => '۱۴۰۱',
                'price' => '۵۲۰,۰۰۰,۰۰۰ تومان',
                'mileage' => '۱۵,۰۰۰',
                'location' => 'تبریز',
                'link' => '/v/quick-r-plus-1401',
                'body_status' => 'عالی'
            ]
        ];

        $this->info("📊 Testing " . count($divarSamples) . " Divar samples:");

        foreach ($divarSamples as $i => $sample) {
            $this->line("   Sample " . ($i + 1) . ": {$sample['title']}");

            $normalized = $normalizer->normalize($sample);

            $this->line("   🔄 Raw → Normalized:");
            $this->line("      Brand: '{$sample['brand']}' → '{$normalized['brand']}'");
            $this->line("      Model: '{$sample['model']}' → '{$normalized['model']}'");
            $this->line("      Year: '{$sample['year']}' → '{$normalized['year']}'");
            $this->line("      Price: '{$sample['price']}' → '{$normalized['price']}'");
            $this->line("      KM: '{$sample['mileage']}' → '{$normalized['km']}'");
            $this->line("      City: '{$sample['location']}' → City ID: {$normalized['city_id']}");

            if (empty($normalized['brand']) || empty($normalized['model']) || empty($normalized['price'])) {
                $this->warn("      ⚠️ Normalization FAILED for this sample!");
                $this->line("      ❌ Missing essential fields");
            } else {
                $this->info("      ✅ Normalization SUCCESS");
            }

            $this->line("");
        }

        // Test city normalization specifically
        $this->info("🗺️ Testing City Mapping:");
        $testCities = ['تهران', 'اصفهان', 'تبریز', 'شیراز', 'مشهد'];

        foreach ($testCities as $city) {
            $cityId = $normalizer->normalizeCityId(['location' => $city]);
            $this->line("   {$city} → City ID: {$cityId}");
        }

        // Test brand normalization
        $this->info("🏭 Testing Brand Mapping:");
        $testBrands = ['پژو', 'تیبا', 'کوییک', 'ساینا', 'پراید'];

        foreach ($testBrands as $brand) {
            $normalizedBrand = $normalizer->normalizeBrand($brand);
            $this->line("   '{$brand}' → '{$normalizedBrand}'");
        }

        $this->info("🎉 Debug Normalization completed!");
    }

    private function testWithRealData()
    {
        $this->info("🔍 Testing with Real Divar Data");

        // Read real data from storage/tmp/divar_tehran_206.json
        $divarDataPath = storage_path('tmp/divar_tehran_206.json');
        if (!file_exists($divarDataPath)) {
            $this->error("❌ Real data file not found: {$divarDataPath}");
            $this->line("   💡 Please place the real data file in storage/tmp/divar_tehran_206.json");
            return;
        }

        $rawData = json_decode(file_get_contents($divarDataPath), true);
        if (!$rawData || !isset($rawData['kt-post-card']['content'])) {
            $this->error("❌ Invalid data structure in real data file");
            return;
        }

        $this->info("📊 Found " . count($rawData['kt-post-card']['content']) . " real items");

        $normalizer = new Normalizer();

        $successfulNormalizations = 0;
        $failedNormalizations = 0;
        $successfulScoring = 0;

        // Test first 5 items
        foreach (array_slice($rawData['kt-post-card']['content'], 0, 5) as $item) {
            if (!isset($item['attributes']['href'])) {
                continue;
            }

            $title = $this->extractTitleFromHtml($item);
            $price = $this->extractPriceFromHtml($item);
            $mileage = $this->extractMileageFromHtml($item);
            $year = $this->extractYearFromHtml($item);

            $this->info("📋 Testing item: " . ($item['attributes']['href'] ?? 'N/A'));
            $this->line("   📝 Title: {$title}");
            $this->line("   💰 Price: {$price}");
            $this->line("   📏 Mileage: {$mileage}");
            $this->line("   📅 Year: {$year}");

            // Skip if essential data is missing
            if (empty($title) || empty($price)) {
                $failedNormalizations++;
                $this->warn("   ❌ Missing essential data (title or price)");
                $this->line("");
                continue;
            }

            // Create test data
            $testData = [
                'source' => 'divar',
                'title' => $title,
                'price' => $price,
                'mileage' => $mileage,
                'year' => $year,
                'location' => 'تهران',
                'link' => $item['attributes']['href'] ?? '',
                'brand' => 'peugeot',
                'model' => '206',
                'body_status' => 'ok'
            ];

            try {
                $normalized = $normalizer->normalize($testData);

                $this->line("   🔄 Normalized result:");
                $this->line("      Brand: '{$normalized['brand']}'");
                $this->line("      Model: '{$normalized['model']}'");
                $this->line("      Price: {$normalized['price']}M");
                $this->line("      Year: {$normalized['year']}");
                $this->line("      KM: {$normalized['km']}");
                $this->line("      City ID: {$normalized['city_id']}");

                if (!empty($normalized['brand']) && !empty($normalized['model']) && !empty($normalized['price'])) {
                    $successfulNormalizations++;
                    $this->line("   ✅ Normalization SUCCESS");

                    // Test scoring
                    try {
                        $scorer = new OpportunityScorer();
                        $score = $scorer->score(
                            $normalized['price'],
                            500, // mock median
                            20,  // mock sample count
                            $normalized['km'],
                            $normalized['year']
                        );

                        if ($score['score'] > 0) {
                            $successfulScoring++;
                            $this->line("   ⭐ Score: {$score['score']} - Reasons: " . implode(', ', $score['reasons']));
                        } else {
                            $this->warn("   ⚠️ Score: 0");
                        }
                    } catch (\Throwable $e) {
                        $this->warn("   ⚠️ Scoring failed: " . $e->getMessage());
                    }
                } else {
                    $failedNormalizations++;
                    $this->warn("   ❌ Normalization failed - missing essential fields");
                }

            } catch (\Throwable $e) {
                $failedNormalizations++;
                $this->error("   ❌ Error: " . $e->getMessage());
            }

            $this->line("");
        }

        $this->info("📈 Results:");
        $this->info("   ✅ Successful normalizations: {$successfulNormalizations}/5");
        $this->info("   ❌ Failed normalizations: {$failedNormalizations}/5");
        $this->info("   ⭐ Successful scoring: {$successfulScoring}/{$successfulNormalizations}");

        if ($successfulNormalizations > 0) {
            $this->info("🎉 Real data test completed successfully!");
        } else {
            $this->warn("⚠️ No successful normalizations - check data extraction logic");
        }
    }

    private function extractTitleFromHtml($item)
    {
        // Extract title from various possible HTML structures
        if (isset($item['content'][0]['content'][0]['content'][0]['content'])) {
            return $item['content'][0]['content'][0]['content'][0]['content'];
        }

        // Try alternative structure
        if (isset($item['content'][0]['content'][0]['content'])) {
            return $item['content'][0]['content'][0]['content'];
        }

        // Try direct content
        if (isset($item['content'][0]['content'])) {
            return $item['content'][0]['content'];
        }

        return '';
    }

    private function extractPriceFromHtml($item)
    {
        // Extract price from various possible HTML structures
        if (isset($item['content'][0]['content'][1]['content'][0]['content'])) {
            return $item['content'][0]['content'][1]['content'][0]['content'];
        }

        // Try alternative structure
        if (isset($item['content'][0]['content'][1]['content'])) {
            return $item['content'][0]['content'][1]['content'];
        }

        // Try direct content
        if (isset($item['content'][0]['content'])) {
            return $item['content'][0]['content'];
        }

        return '';
    }

    private function extractMileageFromHtml($item)
    {
        // Extract mileage from various possible HTML structures
        if (isset($item['content'][0]['content'][1]['content'][1]['content'])) {
            return $item['content'][0]['content'][1]['content'][1]['content'];
        }

        // Try alternative structure
        if (isset($item['content'][0]['content'][1]['content'])) {
            return $item['content'][0]['content'][1]['content'];
        }

        return '';
    }

    private function extractYearFromHtml($item)
    {
        // Try to extract year from title
        $title = $this->extractTitleFromHtml($item);
        if (preg_match('/(\d{4})/', $title, $matches)) {
            return $matches[1];
        }

        // Try to find year in other content fields
        if (isset($item['content'][0]['content'][1]['content'][2]['content'])) {
            $yearContent = $item['content'][0]['content'][1]['content'][2]['content'];
            if (preg_match('/(\d{4})/', $yearContent, $matches)) {
                return $matches[1];
            }
        }

        // Try alternative content structures
        if (isset($item['content'][0]['content'][2]['content'])) {
            $content = $item['content'][0]['content'][2]['content'];
            if (preg_match('/(\d{4})/', $content, $matches)) {
                return $matches[1];
            }
        }

        return ''; // Return empty instead of default
    }

    private function testCityMapping()
    {
        $this->info("🗺️ Testing City Mapping");

        $normalizer = new Normalizer();

        // Test major cities that should have mappings
        $testCities = [
            'تهران',
            'اصفهان',
            'تبریز',
            'شیراز',
            'مشهد',
            'کرج',
            'اهواز',
            'رشت',
            'زاهدان',
            'همدان',
            'یزد',
            'اردبیل',
            'بندرعباس',
            'اراک',
            'زنجان',
            'سنندج',
            'قم',
            'ساری',
            'قزوین',
            'بوشهر',
            'آبادان',
            'خرم‌آباد',
            'سمنان',
            'شاهرود',
            'کاشان',
            'دزفول'
        ];

        $this->info("📊 Testing " . count($testCities) . " cities:");

        $successfulMappings = 0;
        $failedMappings = 0;

        foreach ($testCities as $cityName) {
            $cityId = $normalizer->normalizeCityId(['location' => $cityName]);

            if ($cityId) {
                $successfulMappings++;
                $this->line("   ✅ {$cityName} → City ID: {$cityId}");
            } else {
                $failedMappings++;
                $this->warn("   ❌ {$cityName} → No mapping found");
            }
        }

        $this->info("📈 City Mapping Results:");
        $this->info("   ✅ Successful mappings: {$successfulMappings}/" . count($testCities));
        $this->info("   ❌ Failed mappings: {$failedMappings}/" . count($testCities));

        if ($failedMappings > 0) {
            $this->warn("⚠️ {$failedMappings} cities don't have mappings. This is normal - only major cities are mapped.");
            $this->line("   💡 Major cities (5/26) are mapped: تهران، اصفهان، تبریز، شیراز، مشهد");
        } else {
            $this->info("🎉 All tested city mappings working correctly!");
        }
    }
}
