<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Exception;

class ProductDescriptionController extends Controller
{
    /**
     * Display the description generator view.
     */
    public function index()
    {
        return view('description_generator');
    }

    /**
     * Handle the AI content generation request.
     */
    public function generate(Request $request)
    {
        // 1. Validate the request
        $validator = Validator::make($request->all(), [
            'product_info' => 'required|string|max:2048',
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()->first()], 422);
        }

        $productInfo = $request->input('product_info');

        $isUrl = filter_var($productInfo, FILTER_VALIDATE_URL);
        $contextData = $productInfo;

        if ($isUrl) {
            try {
                $pageResponse = Http::timeout(30)->get($productInfo);
                if ($pageResponse->successful()) {
                    $html = $pageResponse->body();
                    // Strip tags and scripts to extract text
                    $html = preg_replace('@<script[^>]*?>.*?</script>@si', '', $html);
                    $html = preg_replace('@<style[^>]*?>.*?</style>@si', '', $html);
                    $text = strip_tags($html);
                    $text = preg_replace('/\s+/', ' ', $text);
                    $text = substr($text, 0, 30000); // Limit context length to avoid token issues
                    $contextData = "URL: " . $productInfo . "\n\nExtracted Page Content:\n" . $text;
                } else {
                    return response()->json(['error' => 'Failed to retrieve content from the provided URL.'], 400);
                }
            } catch (Exception $e) {
                Log::error('Error fetching URL content: ' . $e->getMessage());
                return response()->json(['error' => 'Invalid URL or unable to access the page.'], 400);
            }
        }

        // 2. Prepare the prompt for the Gemini API
        $systemPrompt = "You are an expert e-commerce copywriter and SEO specialist. Your task is to generate a detailed product description and trending hashtags based on a product name or brief description.
        You MUST return the response as a single, raw JSON object with two keys: `description` and `hashtags`. Do not wrap the JSON in markdown.

        For the `description` key, create a compelling, well-structured HTML block based on the user's input. Use the provided template as a strict guide for the structure. Populate it with accurate or highly plausible specifications for the given product. Be creative and persuasive.
        HTML Template:
        <h1>[Product Name]</h1>
        <p><strong>[Catchy, one-sentence tagline]</strong>. [Further descriptive sentence].</p>
        <h2>📌 Key Specifications</h2>
        <ul>
            <li><strong>Connector:</strong> ...</li>
            <li><strong>Driver Size:</strong> ...</li>
            <li><strong>Impedance:</strong> ...</li>
            <li><strong>Sensitivity:</strong> ...</li>
            <li><strong>Frequency Response:</strong> ...</li>
            <li><strong>Cable Length:</strong> ...</li>
            <li><strong>Microphone & Controls:</strong> ...</li>
            <li><strong>Build Material:</strong> ...</li>
            <li><strong>Compatibility:</strong> ...</li>
        </ul>
        <h2>🔥 Ideal For:</h2>
        <ul>
            <li>[Use case 1]</li>
            <li>[Use case 2]</li>
            <li>[Use case 3]</li>
        </ul>
        <h2>📦 In the Box</h2>
        <ul>
            <li>[Item 1]</li>
            <li>[Item 2]</li>
        </ul>
        
        <p><em>Order your <strong>WIWU EB302 Lightning Earbuds</strong> now from <strong>badudeal.lk</strong>—wired simplicity, reliable sound, fast delivery!</em></p>

        For the `hashtags` key, provide a string of relevant, seo friendly keywords for search engines, separated by commas. Example: 'productname, srilanka, badudeal, gadgets, techtuesday, newarrival, ecommerce'.";

        try {
            // 3. Call the Gemini API
            $apiKey = config('services.gemini.api_key');
            if (empty($apiKey)) {
                return response()->json(['error' => 'Gemini API key is not configured.'], 500);
            }
            //$apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-preview-05-20:generateContent?key={$apiKey}";
            $apiUrl = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={$apiKey}";

            $payload = [
                'contents' => [
                    [
                        'parts' => [
                            ['text' => "Generate content for the following product or based on the following page context:\n{$contextData}"]
                        ]
                    ]
                ],
                'systemInstruction' => [
                    'parts' => [
                        ['text' => $systemPrompt]
                    ]
                ],
                 'generationConfig' => [
                    'responseMimeType' => 'application/json',
                ]
            ];

            $response = Http::timeout(120)->post($apiUrl, $payload);

            if ($response->failed()) {
                Log::error('Gemini API request failed for description generation', ['status' => $response->status(), 'response' => $response->body()]);
                return response()->json(['error' => 'Failed to generate content with AI. Status: ' . $response->status()], 500);
            }

            $generatedContent = $response->json('candidates.0.content.parts.0.text');
            $decodedContent = json_decode($generatedContent, true);

            if (json_last_error() !== JSON_ERROR_NONE || !isset($decodedContent['description']) || !isset($decodedContent['hashtags'])) {
                Log::error('Failed to decode JSON from Gemini for description', ['response' => $generatedContent]);
                return response()->json(['error' => 'Could not parse the AI-generated content.'], 500);
            }

            return response()->json($decodedContent);

        } catch (Exception $e) {
            Log::error('Error in description generation process', ['message' => $e->getMessage()]);
            return response()->json(['error' => 'An unexpected error occurred.'], 500);
        }
    }
}
