<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class ImportArtworkHashes extends Command
{
    protected $signature = 'artworks:import-hashes {file=artworks_hash_skinbase.csv} {--start=0} {--limit=0}';
    protected $description = 'Import artwork hash, file_ext and thumb_ext from CSV (id,hash,file_ext,thumb_ext)';

    public function handle(): int
    {
        $file = $this->argument('file');
        $path = base_path($file);

        if (!is_readable($path)) {
            $this->error("CSV file not readable: {$path}");
            return 1;
        }

        $handle = fopen($path, 'r');
        if (!$handle) {
            $this->error('Unable to open CSV file');
            return 1;
        }

        // Read header
        $header = fgetcsv($handle);
        if ($header === false) {
            $this->error('CSV appears empty');
            fclose($handle);
            return 1;
        }

        $start = (int) $this->option('start');
        $limit = (int) $this->option('limit');
        $rowIndex = 0;
        $bar = null;

        // Optionally count lines for progress bar
        if ($limit === 0) {
            // We'll not determine total to keep memory low
        }

        while (($row = fgetcsv($handle)) !== false) {
            $rowIndex++;
            if ($rowIndex <= $start) {
                continue;
            }
            if ($limit > 0 && ($rowIndex - $start) > $limit) {
                break;
            }

            // Expecting columns: id,hash,file_ext,thumb_ext
            $id = isset($row[0]) ? trim($row[0], "\" ") : null;
            $hash = isset($row[1]) ? trim($row[1], "\" ") : null;
            $file_ext = isset($row[2]) ? trim($row[2], "\" ") : null;
            $thumb_ext = isset($row[3]) ? trim($row[3], "\" ") : null;

            if (empty($id)) {
                continue;
            }

            // Normalize null strings
            if (strtoupper($hash) === 'NULL') $hash = null;
            if (strtoupper($file_ext) === 'NULL') $file_ext = null;
            if (strtoupper($thumb_ext) === 'NULL') $thumb_ext = null;

            try {
                DB::table('artworks')->where('id', $id)->limit(1)->update([
                    'hash' => $hash,
                    'file_ext' => $file_ext,
                    'thumb_ext' => $thumb_ext,
                ]);
            } catch (\Throwable $e) {
                // Log and continue on duplicate / other DB errors
                $this->error("Row {$rowIndex} (id={$id}) failed: " . $e->getMessage());
                continue;
            }

            if ($rowIndex % 500 === 0) {
                $this->info("Processed {$rowIndex} rows");
            }
        }

        fclose($handle);
        $this->info('Import complete.');
        return 0;
    }
}
