<?php

namespace Modules\ProductCompat\Console;

use App\Product;
use Illuminate\Console\Command;
use Modules\ProductCompat\Entities\PcDataCandidate;
use Modules\ProductCompat\Entities\Services\CompatibilityLinker;

/**
 * FINAL cross-product compatibility phase — run AFTER products are cleaned and
 * their part numbers are trustworthy:
 *   1. autoLinkShared — link products that share a part number / device model.
 *   2. Resolve every pending 'compatible' candidate (AI-suggested ref) to a real
 *      product id and link it (matches that failed earlier can now succeed).
 * All links land needs_review=true → confirm them in the Review Queue.
 *
 *   php artisan productcompat:match-compatibility --business=1
 */
class MatchCompatibility extends Command
{
    protected $signature = 'productcompat:match-compatibility
        {--business= : Limit to one business id}
        {--limit=0 : Max products to auto-link (0 = all)}';

    protected $description = 'Cross-product compatibility matching (shared data + AI refs) — the final phase.';

    public function handle(CompatibilityLinker $linker): int
    {
        $businessId = $this->option('business') ? (int) $this->option('business') : null;
        $limit = max(0, (int) $this->option('limit'));

        // ---- 1. Shared-data auto-link across the catalogue ----
        $this->info('Auto-linking products that share a part number or device model…');
        $shared = 0;
        $count = 0;
        Product::when($businessId, fn ($q) => $q->where('business_id', $businessId))
            ->select('id', 'business_id')
            ->orderBy('id')
            ->chunkById(500, function ($rows) use ($linker, &$shared, &$count, $limit) {
                foreach ($rows as $p) {
                    $shared += $linker->autoLinkShared((int) $p->business_id, (int) $p->id);
                    $count++;
                    if ($limit > 0 && $count >= $limit) {
                        return false; // stop the chunk walk
                    }
                }
            });
        $this->info("  Shared-data links created: {$shared} (scanned {$count} products).");

        // ---- 2. Resolve pending AI-suggested compatible refs ----
        $this->info('Matching AI-suggested compatible products to the catalogue…');
        $linked = 0;
        $resolved = 0;
        PcDataCandidate::where('field', 'compatible')->where('status', 'pending')
            ->when($businessId, fn ($q) => $q->where('business_id', $businessId))
            ->orderBy('id')
            ->chunkById(500, function ($cands) use ($linker, &$linked, &$resolved) {
                foreach ($cands as $c) {
                    $ref = (array) $c->extra;
                    if (empty($ref['match_by']) || empty($ref['value'])) {
                        continue;
                    }
                    $made = $linker->linkAiRefs((int) $c->business_id, (int) $c->product_id, [$ref], 'ai');
                    if ($made > 0) {
                        $linked += $made;
                        $resolved++;
                        // Suggestion materialised into a review-first link → done.
                        $c->update(['status' => 'applied', 'applied_at' => now()]);
                    }
                    // No match yet → leave pending for a future re-run.
                }
            });
        $this->info("  AI refs resolved: {$resolved} (→ {$linked} links). Unmatched refs stay pending.");

        $this->info('Done. Review the new compatibility links in the Review Queue.');

        return self::SUCCESS;
    }
}
