<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Jobs\BamaPullLatestJob;
use App\Jobs\DivarScrapeJob;
use App\Jobs\ScoreOpportunitiesJob;
use App\Jobs\PushSchedulerJob;

class RunAdsSystem extends Command
{
    protected $signature = 'ads:run {--test : Use test data} {--force : Force run}';
    protected $description = 'Run the complete ads system';

    public function handle()
    {
        $this->info('🚀 Running ads system...');
        $this->newLine();

        // Check if system is already running
        if (!$this->option('force')) {
            $lastRun = DB::table('ads_raw')
                ->where('created_at', '>', now()->subMinutes(10))
                ->exists();

            if ($lastRun) {
                $this->warn('⚠️  System was recently run. Use --force to run anyway.');
                return 0;
            }
        }

        // Step 1: Data Collection
        $this->info('📥 Step 1: Data Collection');
        $this->collectData();

        // Step 2: Scoring
        $this->info('🎯 Step 2: Scoring');
        $this->scoreOpportunities();

        // Step 3: Push Scheduling
        $this->info('📤 Step 3: Push Scheduling');
        $this->schedulePushes();

        // Step 4: Show Results
        $this->info('📊 Step 4: Results');
        $this->showResults();

        $this->info('✅ Ads system run completed!');
        return 0;
    }

    private function collectData()
    {
        // Collect from Bama
        $this->info('  📥 Collecting from Bama...');
        if ($this->option('test')) {
            BamaPullLatestJob::dispatch(1, true);
        } else {
            BamaPullLatestJob::dispatch(1, false);
        }

        // Collect from Divar
        $profiles = DB::table('scrape_profiles')
            ->where('enabled', true)
            ->get();

        if ($profiles->isNotEmpty()) {
            $this->info('  📥 Collecting from Divar...');
            foreach ($profiles as $profile) {
                DivarScrapeJob::dispatch($profile->url, $this->option('test'));
            }
        }

        // Wait for collection
        $this->info('  ⏳ Waiting for data collection...');
        sleep(10);

        $rawCount = DB::table('ads_raw')->where('created_at', '>', now()->subHour())->count();
        $this->info("  ✅ Collected {$rawCount} raw ads");
    }

    private function scoreOpportunities()
    {
        $this->info('  🎯 Scoring opportunities...');
        ScoreOpportunitiesJob::dispatch();

        // Wait for scoring
        sleep(5);

        $opportunitiesCount = DB::table('opportunities')->where('created_at', '>', now()->subHour())->count();
        $reviewedCount = DB::table('opportunities')->where('status', 'reviewed')->where('created_at', '>', now()->subHour())->count();

        $this->info("  ✅ Scored {$opportunitiesCount} opportunities ({$reviewedCount} reviewed)");
    }

    private function schedulePushes()
    {
        $this->info('  📤 Scheduling pushes...');
        PushSchedulerJob::dispatch();

        // Wait for scheduling
        sleep(2);

        $scheduledCount = DB::table('opportunities')->where('status', 'scheduled')->where('created_at', '>', now()->subHour())->count();
        $this->info("  ✅ Scheduled {$scheduledCount} pushes");
    }

    private function showResults()
    {
        $this->newLine();
        $this->info('📊 System Run Results:');

        $results = [
            ['Raw Ads (last hour)', DB::table('ads_raw')->where('created_at', '>', now()->subHour())->count()],
            ['New Opportunities', DB::table('opportunities')->where('created_at', '>', now()->subHour())->count()],
            ['Reviewed Opportunities', DB::table('opportunities')->where('status', 'reviewed')->where('created_at', '>', now()->subHour())->count()],
            ['Scheduled Pushes', DB::table('opportunities')->where('status', 'scheduled')->where('created_at', '>', now()->subHour())->count()],
            ['Total Opportunities', DB::table('opportunities')->count()],
            ['High Score (≥0.8)', DB::table('opportunities')->where('score', '>=', 0.8)->count()],
            ['Medium Score (0.6-0.8)', DB::table('opportunities')->whereBetween('score', [0.6, 0.8])->count()],
            ['Low Score (<0.6)', DB::table('opportunities')->where('score', '<', 0.6)->count()],
        ];

        $this->table(['Metric', 'Count'], $results);

        // Show top opportunities
        $this->newLine();
        $this->info('🏆 Top Opportunities:');
        $topOpportunities = DB::table('opportunities')
            ->where('status', 'reviewed')
            ->orderBy('score', 'desc')
            ->limit(5)
            ->get(['code', 'brand', 'model', 'year', 'price', 'score']);

        $this->table(
            ['Code', 'Brand', 'Model', 'Year', 'Price', 'Score'],
            $topOpportunities->map(function ($opp) {
                return [
                    $opp->code,
                    $opp->brand,
                    $opp->model,
                    $opp->year,
                    number_format($opp->price) . 'M',
                    number_format($opp->score, 2)
                ];
            })->toArray()
        );
    }
}
