<?php
require __DIR__ . '/../vendor/autoload.php';
$app = require __DIR__ . '/../bootstrap/app.php';
$kernel = $app->make(Illuminate\Contracts\Console\Kernel::class);
$kernel->bootstrap();

use App\Models\Product;

$imageDir = __DIR__ . '/../public/images';
$files = array_values(array_filter(scandir($imageDir), function($f){ return !in_array($f, ['.','..']); }));
$normFiles = [];
foreach ($files as $f) {
    $norm = preg_replace('/[^a-z0-9]/', '', strtolower($f));
    $normFiles[$f] = $norm;
}

function normalize($s) {
    return preg_replace('/[^a-z0-9]/', '', strtolower($s));
}

$updated = [];
foreach (Product::all() as $p) {
    $name = $p->name ?? '';
    $color = $p->color ?? '';
    $candidates = [];
    $targetTokens = array_filter(array_map('trim', explode(' ', strtolower($name))));
    $targetNorm = normalize($name . ' ' . $color);

    foreach ($normFiles as $file => $norm) {
        $score = 0;
        // if normalized product name is substring of file name
        if (strpos($norm, normalize($name)) !== false) $score += 5;
        if (strpos($norm, normalize($color)) !== false) $score += 3;
        // count shared tokens
        foreach ($targetTokens as $t) {
            if ($t === '') continue;
            if (strpos($norm, preg_replace('/[^a-z0-9]/','', $t)) !== false) $score += 1;
        }
        // penalty for very short matches
        if (strlen($norm) < 5) $score -= 2;
        if ($score > 0) $candidates[$file] = $score;
    }

    if (!empty($candidates)) {
        arsort($candidates);
        $best = array_key_first($candidates);
        $bestScore = $candidates[$best];
        if ($bestScore >= 3) {
            $p->image_url = '/images/' . $best;
            $p->save();
            $updated[] = [$p->id, $p->name, $best, $bestScore];
        }
    }
}

foreach (array_slice($updated,0,20) as $u) {
    echo "Updated product {$u[0]} ({$u[1]}) -> {$u[2]} (score={$u[3]})\n";
}

echo "Total updated: " . count($updated) . "\n";
