from dotenv import load_dotenv
from crewai import Agent, LLM, Task, Crew

from fastapi import FastAPI, Query
from pydantic import BaseModel
from crewai import Agent, Task, Crew
from typing import Dict
import os 
import re
import json 

load_dotenv()

# Initialize FastAPI app
app = FastAPI(title="Amazon Listing Generator API", version="1.0")

vision_oai_llm = LLM(
    model= "openai/gpt-4o-mini", #"gemini/gemini-1.5-pro-latest",  #"openai/gpt-4o-mini" , #"openrouter/anthropic/claude-3-haiku", #"openai/gpt-4o-mini",
    temperature=0,
    # base_url="https://api.openai.com/v1",
    api_key= os.getenv('OPEN_AI_API_KEY') #os.getenv('OPEN_AI_API_KEY')
)

# Define Agents
image_analyst = Agent(
    role="Amazon Product Listing Expert",
    goal="Analyze product images and generate Amazon optimized product title, description, bullets and keywords.",
    backstory="You are an Amazon SEO and conversion optimization expert with years of experience in crafting high-performing product listings. Your expertise lies in analyzing product images and using them as the foundation for compelling, keyword-rich Amazon product titles, bullet points, and descriptions. With a keen eye for detail and a deep understanding of buyer psychology, you transform raw product visuals into listings that rank higher, convert better, and drive maximum revenue. You have an in-depth knowledge of Amazon’s A9 algorithm, ensuring that your content is not just engaging but also search-optimized. You write enaging content and utilize all the keywords.",
    multimodal=True,
    llm=vision_oai_llm
)

reviewer_agent = Agent(
    role="Amazon Listing Reviewer",
    goal="Ensure that the product image aligns with the product title, description, keywords, and key features provided by the Amazon Product Listing Expert. Verify that all listing elements are accurate, compliant, and optimized for conversions while maintaining consistency and credibility.", 
    backstory="As an Amazon e-commerce specialist, you are an expert in reviewing if the content is engaging. You are an expert in verifying, if the written title, description and bullets have all the keywords. You also verify the character count for title, description and bullets.",
    multimodal=True,
    llm=vision_oai_llm  # Using a cheaper text model
)

# Define API Response Model
class AmazonListing(BaseModel):
    title: str
    description: str
    key_features: Dict[int, str]
    review_status: str

@app.get("/generate-listing")
async def generate_listing(image_url: str = Query(..., description="URL of the product image")):
    """Generate an Amazon-optimized product listing from an image."""

    # Define Tasks
    generate_task = Task(
        description="""
        Analyze the product image at {image_url} and generate the following for an Amazon listing:
        1. **keywords based** on application of the sign and append "neon light", "neon signs", "neon signage", "personalized neon signs","custom design neon signs", "custom fluorescent signs", "custom neon sign", "neon lights signs", "neon and light", "led neon signs", "custom led signs", "personalized led sign", "custom led neon", "custom neon lights", "custom made neon lights", "outdoor neon signs"
        2. **Product Title** (190-200 characters, Must follow this exact format: Brand Name ("Everything Neon"), Product Name (e.g., "Good Vibes Neon Sign"), USP (Unique Selling Proposition - e.g., "Energy Efficient LED Light"), Color (e.g., "Warm White"))
        3. **Product Description** (Between 1950-2000 characters)
        4. **Key Features** (240-250 characters, 5 bullet points)
        
        Follow Amazon's guidelines:
        - Title must be capitalized correctly and under 190-200 characters.
        - No promotional claims, special characters, or time-sensitive phrases.
        - Description should be structured, covering key benefits and use cases.
        - Ensure all the keywords are utilized in the content at least once
        - Content should sound like human and not AI written
        - Content should be engaging for the viewer
        - All bullets and description should be written keeping customer benefits in mind
        - Key features should be concise, focusing on material, dimensions, and unique selling points.
        """,
        
        expected_output="""
            "title": "Everything Neon WINE BAR Neon Sign - Bright LED Wall Light for Bars, Lounges, Restaurants, Pubs, Cafes & Wine Shops - Energy Efficient LED Neon Decor - Red",
            "description": "Make your bar, lounge, restaurant, or wine shop stand out with the Everything Neon WINE BAR Neon Sign, a brilliantly illuminated wine sign that enhances any space. This LED neon wine sign delivers a vibrant red glow with a sleek white border, adding a modern, inviting look to any bar signage setup. Designed for indoor use, this energy-efficient neon sign is the perfect addition to bars, lounges, wine shops, cafes, restaurants, and pubs. Built using durable silicone tubing and high-quality acrylic backing, this custom neon sign offers more than 50,000 hours of bright, steady illumination. Unlike traditional neon lights, this neon light for bar is powered by a low-voltage 12V adapter, eliminating flickering and overheating. The adapter ensures constant brightness without the need for batteries, making this an ideal business storefront sign for commercial or home use. With easy wall-mounting installation, this wine shop display light includes all necessary hardware for quick setup. The dimmable function allows you to adjust brightness levels to create the perfect atmosphere, whether for an intimate wine bar setting, a lively restaurant ambiance, or a stylish lounge LED sign. This restaurant neon signage is ideal for enhancing visibility, drawing customers, and improving décor. Designed for wine lovers, business owners, and interior designers, this cafe bar neon light transforms any location into a stylish and welcoming space. Ideal for personal use, businesses, or gifting, this custom neon sign adds a touch of personality and charm to any venue. Enjoy peace of mind with our 1-year warranty and energy-efficient operation, making it the ultimate bar decor light.",
            "key_features": [
                "Vibrant LED Bar Signage - This WINE BAR Neon Sign is a bold, illuminated wine sign designed for bars, lounges, restaurants, cafes, pubs, and wine shops, adding a stylish, inviting glow that enhances ambiance and draws attention.",
                "Premium LED Neon Build - Made from high-quality acrylic backing and durable silicone tubing, this LED neon wine sign ensures over 50,000 hours of illumination. It's a reliable, long-lasting bar signage solution.",
                "Energy-Efficient & Safe - This neon light for bar runs on low-voltage 12V power, using an efficient LED adapter for flicker-free, battery-free, and heat-free operation. Perfect for commercial or home use as a business storefront sign.",
                "Easy Installation & Customizable Brightness - Comes with mounting hardware and a dimmer, making setup simple. Adjust the wine shop display light to create the perfect brightness level for any setting, from restaurants to lounges.",
                "Perfect for Businesses & Personal Use - This restaurant neon signage is ideal for bars, clubs, cafes, wine shops, pubs, home bars, and commercial displays. The cafe bar neon light makes a great gift for wine lovers and bar owners."
            ]
        """,
        agent=image_analyst
    )
    
    review_task = Task(
        description="""
        Analyze the image at {image_url} for an Amazon listing and then Review the generated Amazon product title, description, and key features by Amazon Product Listing Expert Agent
        
        1. First and foremast and most important : check if the given image matches the title and description given by agent - if not , dissaprove immediately.
        2. **Title Check** - Is it under 200 characters, properly formatted, and SEO-friendly?
        3. **Description Check** - Does it follow Amazon's guidelines, avoiding promotional phrases?
        4. **Key Features Check** - Are they structured correctly and benefit-driven?
        5. **Accuracy Check** - Ensure details match the product and are not misleading.
        6. show the keywords that are used in the content

        - First and foremast and most important : check if the given image matches the title and description given by agent - if not , dissaprove immediately.
        - **keywords based** on application of the sign and append "neon light", "neon signs", "neon signage", "personalized neon signs","custom design neon signs", "custom fluorescent signs", "custom neon sign", "neon lights signs", "neon and light", "led neon signs", "custom led signs", "personalized led sign", "custom led neon", "custom neon lights", "custom made neon lights", "outdoor neon signs"
        - **Product Title** (190-200 characters, Must follow this exact format: Brand Name ("Everything Neon"), Product Name (e.g., "Good Vibes Neon Sign"), USP (Unique Selling Proposition - e.g., "Energy Efficient LED Light"), Color (e.g., "Warm White"))
        - **Product Description** (Between 1950-2000 characters)
        - **Key Features** (240-250 characters, 5 bullet points)
        - Title must be capitalized correctly and under 190-200 characters.
        - No promotional claims, special characters, or time-sensitive phrases.
        - Description should be structured, covering key benefits and use cases.
        - Ensure all the keywords are utilized in the content at least once
        - Content should sound like human and not AI written
        - Content should be engaging for the viewer
        - All bullets and description should be written keeping customer benefits in mind
        - Key features should be concise, focusing on material, dimensions, and unique selling points.
        
        - If it meets all criteria (including the image), approve the listing.
        - If revisions are needed, provide specific feedback.
        """,
        expected_output="""
            A JSON object with 'keywords', 'title', 'description', 'key_features' and 'review_status' fields.
            example output:
            {{
            "title": "<Generated Amazon-approved title>",
            "description": "<Amazon-optimized product description>",
            "key_features": [
                "<Feature 1>",
                "<Feature 2>",
                "<Feature 3>",
                "<Feature 4>",
                "<Feature 5>"
            ],
            "review_status": "<approved> or <not_approved>"
            }}
            """,
        agent=reviewer_agent,
        output_json=AmazonListing
    )
    
    # Create Crew
    crew = Crew(
        agents=[image_analyst, reviewer_agent],
        tasks=[generate_task, review_task],
        verbose=True
    )

    # Execute Crew with Image Input
    result = crew.kickoff(inputs={"image_url": image_url})

    print(f"crewai result : {result}")

    try:
        result['review_status']
        return result
    except Exception as e :
        print(f"JSON failed. Extracting manually: {e}")
        pattern = r'json\s*({.*?})'  # Match "json" followed by optional whitespace and a JSON object
        match = re.search(pattern, result.raw, re.DOTALL)
        
        if match:
            json_string = match.group(1)
            try:
                result = json.loads(json_string)
            except json.JSONDecodeError as e:
                return f"Error decoding JSON: {e}"
        else:
            result = {}
            print("JSON object not found.")

        return result


# Usage : 
# uvicorn fast_api:app --reload --port 8001
