<?php

namespace Modules\ProductCompat\Console;

use App\Product;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Modules\ProductCompat\Entities\PcPartNumber;

/**
 * Split the WHOLE catalog into numbered batch files for offline enrichment with
 * an AI assistant (e.g. Claude Code) — no online AI provider or SearXNG needed.
 * Also drops a PROMPT.md the operator pastes alongside each batch, and a README.
 *
 *   php artisan productcompat:export-batches --size=300 --dir=storage/app/pc_batches
 *
 * Produces: batch_0001.json … batch_NNNN.json + PROMPT.md + README.txt.
 * Enrich each → save as batch_XXXX.enriched.json → import with:
 *   php artisan productcompat:import-enrichment storage/app/pc_batches
 */
class ExportBatches extends Command
{
    protected $signature = 'productcompat:export-batches
        {--business= : Business id (default: all)}
        {--size=300 : Products per batch file}
        {--missing : Only products missing a part number, description or image}
        {--dir= : Output directory (default: storage/app/pc_batches)}';

    protected $description = 'Split the whole catalog into JSON batches for offline AI enrichment.';

    public function handle(): int
    {
        $size = max(1, (int) $this->option('size'));
        $dir  = rtrim($this->option('dir') ?: storage_path('app/pc_batches'), '/\\');
        if (! is_dir($dir)) {
            @mkdir($dir, 0755, true);
        }

        // Full rows (custom fields + category needed by ProductContext).
        $q = Product::query();
        if ($b = $this->option('business')) {
            $q->where('business_id', (int) $b);
        }
        if ($this->option('missing')) {
            $q->where(function ($w) {
                $w->whereNotExists(fn ($s) => $s->select(DB::raw(1))->from('pc_part_numbers')
                        ->whereColumn('pc_part_numbers.product_id', 'products.id'))
                    ->orWhereNull('product_description')->orWhere('product_description', '')
                    ->orWhereNull('image')->orWhere('image', '');
            });
        }

        $batch = [];
        $fileNo = 0;
        $total = 0;

        $flush = function () use (&$batch, &$fileNo, $dir) {
            if (empty($batch)) {
                return;
            }
            $fileNo++;
            $path = $dir . '/batch_' . str_pad((string) $fileNo, 4, '0', STR_PAD_LEFT) . '.json';
            file_put_contents($path, json_encode(array_values($batch), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE));
            $batch = [];
        };

        $q->orderBy('id')->chunkById(500, function ($rows) use (&$batch, &$total, $size, $flush) {
            foreach ($rows as $p) {
                $ctx = \Modules\ProductCompat\Entities\Services\ProductContext::gather($p);
                $batch[] = [
                    'id'            => (int) $p->id,
                    'sku'           => $ctx['sku'],
                    'name'          => $ctx['name'],
                    'brand'         => $ctx['brand'],
                    'category'      => trim($ctx['category'] . ' / ' . $ctx['sub_category'], ' /'),
                    'description'   => $ctx['description'],
                    'custom_fields' => $ctx['custom_fields'],
                    'existing_identifiers' => $ctx['existing_identifiers'],
                    'has_image'     => ! empty($p->image),
                ];
                $total++;
                if (count($batch) >= $size) {
                    $flush();
                }
            }
        });
        $flush();

        file_put_contents($dir . '/PROMPT.md', $this->promptText());
        file_put_contents($dir . '/README.txt', $this->readmeText($fileNo, $size));

        $this->info("Exported {$total} product(s) into {$fileNo} batch file(s) of up to {$size} → {$dir}");
        $this->line('Prompt for the AI assistant: ' . $dir . '/PROMPT.md');
        $this->line('When enriched files are ready: php artisan productcompat:import-enrichment ' . $dir);

        return self::SUCCESS;
    }

    protected function promptText(): string
    {
        return <<<'MD'
# Product enrichment + cleanup task

You are cleaning up and completing spare-parts / electronics products (mostly
laptop batteries, chargers, accessories). Each input product includes: name, sku,
brand, category, description, `custom_fields` (CF1–6 — blobs that hold many part
numbers/serials), and `existing_identifiers` (the part numbers/serials currently
attributed to the product). For EACH product return an enriched object.

## Per-product task (do this for every product)
1. **CLEAN UP** — for each value in `existing_identifiers`, decide if it truly
   belongs to THIS exact product. If it does NOT, add a correction with
   `kind:"remove_part_number"` (or `remove_serial`), the value, and a short
   reason. Never flag a value that genuinely belongs.
2. **COMPLETE** — add real `part_numbers` this product is missing (read the
   custom fields + your knowledge). `type` = mpn|oem|model_code|other.
3. **DEVICE FIT** — `device_models`: the devices this part fits (brand/series/model).
4. **DESCRIBE** — `description` (factual, <=1000 chars, no fluff) + `specs`
   (Voltage, Capacity, Chemistry, Cells, Color…).
5. **COMPATIBLE PRODUCTS** — `compatible_products`: OTHER products this one is
   interchangeable with / replaces, each identified so we can match it to the
   catalogue: `match_by` = sku | part_number | name, `value` = that identifier,
   `relation` = compatible | replacement | accessory.

## Rules
- Only include data you are genuinely confident about; omit anything uncertain.
- Do NOT invent image URLs — images are handled separately.

## Return format
Return ONLY a JSON array, one object per input product, each:
```json
{
  "id": 123,
  "part_numbers": [{"value":"L09S3B11","type":"oem"}],
  "device_models": [{"brand":"Lenovo","series":"IdeaPad","model":"S10-2"}],
  "barcodes": [],
  "description": "Replacement Li-ion battery for …",
  "specs": [{"label":"Voltage","value":"11.1 V"},{"label":"Capacity","value":"5200 mAh"}],
  "corrections": [{"kind":"remove_part_number","current_value":"XYZ999","problem":"belongs to a different model"}],
  "compatible_products": [{"match_by":"part_number","value":"L09C3B11","relation":"replacement"}]
}
```
Keep the `id` from the input. Save your output as `batch_XXXX.enriched.json`
(same number as the input file).
MD;
    }

    protected function readmeText(int $files, int $size): string
    {
        return "ProductCompat offline enrichment\n"
            . "================================\n\n"
            . "{$files} batch file(s), up to {$size} products each.\n\n"
            . "For each batch_XXXX.json:\n"
            . "  1. Give the AI assistant PROMPT.md + the batch file.\n"
            . "  2. Save its JSON output as batch_XXXX.enriched.json in this folder.\n\n"
            . "Then import everything at once (imports all *.enriched.json here):\n"
            . "  php artisan productcompat:import-enrichment " . '"' . storage_path('app/pc_batches') . '"' . "\n\n"
            . "Results land review-first in Product Compatibility -> Review Queue.\n";
    }
}
