<?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 RunAdsPipeline extends Command
{
    protected $signature = 'ads:pipeline {--force : Force run even if recently run}';
    protected $description = 'Run the complete ads pipeline';

    public function handle()
    {
        $this->info('🚀 Starting ads pipeline...');

        // Check if recently run (unless forced)
        if (!$this->option('force')) {
            $lastRun = DB::table('ads_raw')
                ->where('created_at', '>', now()->subMinutes(30))
                ->exists();

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

        // Step 1: Collect data from Bama
        $this->info('📥 Collecting data from Bama...');
        BamaPullLatestJob::dispatch(1, false);

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

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

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

        // Step 3: Score opportunities
        $this->info('🎯 Scoring opportunities...');
        ScoreOpportunitiesJob::dispatch();

        // Wait for scoring to complete
        sleep(5);

        // Step 4: Run push scheduler
        $this->info('📤 Running push scheduler...');
        PushSchedulerJob::dispatch();

        // Step 5: Show results
        $this->showResults();

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

    private function showResults()
    {
        $rawCount = DB::table('ads_raw')->where('created_at', '>', now()->subHour())->count();
        $opportunitiesCount = DB::table('opportunities')->where('created_at', '>', now()->subHour())->count();
        $reviewedCount = DB::table('opportunities')->where('status', 'reviewed')->where('created_at', '>', now()->subHour())->count();
        $scheduledCount = DB::table('opportunities')->where('status', 'scheduled')->where('created_at', '>', now()->subHour())->count();

        $this->info('📊 Pipeline results:');
        $this->table(
            ['Metric', 'Count'],
            [
                ['Raw Ads (last hour)', $rawCount],
                ['New Opportunities', $opportunitiesCount],
                ['Reviewed Opportunities', $reviewedCount],
                ['Scheduled for Push', $scheduledCount],
                ['Total Opportunities', DB::table('opportunities')->count()],
                ['High Score (≥0.8)', DB::table('opportunities')->where('score', '>=', 0.8)->count()],
            ]
        );
    }
}
