<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;

class AiLotAnalyzer
{
    /**
     * Analyze an uploaded image of a sports card or memorabilia item.
     * Returns structured JSON suitable for storing on Lot::ai_analysis
     * and for setting the starting_bid.
     */
    public function analyze(string $imagePathOrUrl): array
    {
        try {
            // In production replace with real vision call (xAI Grok Vision, OpenAI, Claude, etc.)
            // Example structure matches the mockup in 06-ai-item-analysis.png

            // --- MOCK for local development / demo ---
            // Replace this entire block with real API call when keys are ready.
            $mockIdentification = [
                'item_type' => 'sports_card',
                'set' => '2021 Topps Update',
                'insert' => 'Vintage Stock',
                'card_number' => 'US148',
                'player' => 'Daniel Vogelbach',
                'serial_number' => '99',
                'print_run' => 99,
                'team' => 'Milwaukee Brewers',
                'year' => 2021,
            ];

            $comps = $this->lookupComps($mockIdentification);

            $marketValue = $comps['market_value'] ?? 50.00;

            $suggested = [
                'conservative' => round($marketValue * 0.40, 2), // 40%
                'recommended'  => round($marketValue * 0.50, 2), // 50%
                'aggressive'   => round($marketValue * 0.60, 2), // 60%
            ];

            return [
                'identification' => $mockIdentification,
                'comps' => $comps,
                'suggested_starting_bids' => $suggested,
                'confidence' => 0.92,
                'condition_notes' => [
                    'corners' => 'sharp with light wear',
                    'surface' => 'clean with minor print texture',
                    'centering' => 'well centered, slight top edge softness',
                    'overall' => 'NM-MT (8.5)',
                ],
                'auto_categories' => ['Sports Cards', 'Baseball', 'Topps'],
                'analyzed_at' => now()->toIso8601String(),
                'engine' => 'CapitalForge AI v1.2.0 (mock)',
            ];
        } catch (\Throwable $e) {
            Log::error('AiLotAnalyzer failed', ['error' => $e->getMessage()]);
            throw $e;
        }
    }

    /**
     * Lookup recent sales / market value.
     * In production this would hit a comps database, eBay sold API, or internal JSON store.
     */
    protected function lookupComps(array $identification): array
    {
        // Example: query a local JSON file or DB table of recent sales
        // keyed by player + set + card_number

        return [
            'lowest_sale' => 10.90,
            'market_value' => 10.90,
            'highest_sale' => 10.90,
            'sales_count_30d' => 3,
            'source' => 'internal_comps',
            'last_updated' => now()->subHours(2)->toIso8601String(),
        ];
    }

    /**
     * Convenience: set the lot starting bid from AI recommendation.
     */
    public function applyRecommendedStart(\App\Models\Lot $lot, string $tier = 'recommended'): void
    {
        $analysis = $lot->ai_analysis ?? $this->analyze($lot->getFirstMediaPath('primary') ?? '');
        $bid = $analysis['suggested_starting_bids'][$tier] ?? $lot->starting_bid;

        $lot->update([
            'starting_bid' => $bid,
            'current_bid' => $bid,
            'ai_analysis' => $analysis,
        ]);
    }
}
