from googleapiclient.discovery import build
import streamlit as st
import requests
from openai import OpenAI
import os
import bentoml
from pathlib import Path

client = OpenAI()
client.key = os.getenv("OPENAI_API_KEY")
GOOGLE_API_DEV_KEY = os.getenv("GOOGLE_API_DEV_KEY")


def search_amazon(query: str, num: int = 10) -> str:
    service = build(
        "customsearch", "v1", developerKey=GOOGLE_API_DEV_KEY
    )

    res = (
        service.cse()
        .list(
            q=query,
            cx="103114c8487ce4aa1",
            num=num,
        )
        .execute()
    )

    links = ""

    if res['items'] is None or res['items'] == []:
        return "No items found"
    for item in res['items']:
        links += f"- [{item['title']}]({item['link']})\n"

    return links

def remove_quotes(input_string):
    return input_string.replace('"', '')

import re

def append_tag_to_amazon_url(input_string):
    pattern = r'(https?://www\.amazon\.com[^)]*)'

    def append_tag(match):
        url = match.group(0)
        if '?' in url:
            return url + '&tag=dpang-20'
        else:
            return url + '?tag=dpang-20'

    return re.sub(pattern, append_tag, input_string)

import requests
import os

def downloadImage(image_url):

    # Extract the file name and extension from the URL
    file_name = os.path.basename(image_url)

    # Local file path where you want to save the image
    local_file_path = os.path.join('./', file_name)

    # Send a GET request to the URL
    response = requests.get(image_url)

    # Check if the request was successful (status code 200)
    if response.status_code == 200:
        # Open a local file in write-binary ('wb') mode
        with open(local_file_path, 'wb') as file:
            # Write the content of the response to the file
            file.write(response.content)
        print(f"Image downloaded and saved as {local_file_path}")
    else:
        print(f"Failed to download the image. Status code: {response.status_code}")

    return file_name

# Streamlit interface
st.title('Vision SHop')
url = st.text_input('Enter the url link to an image ( Example: https://images.ctfassets.net/7rldri896b2a/4augh14at0OZJuEhbWF0av/09dd54fe6543a36f2832f79cc51adad1/spc-bathdecor.jpg )', '')
#url = st.text_input('Enter the url link to the image', 'Image URL')
if st.button('Shop'):
    # Make a POST request
    try:
        basename=downloadImage(url)
        result=""
        with bentoml.SyncHTTPClient("https://blip-image-captioning-r2hq-org-rag-hackathon--gcp-us-central-1.mt-guc1.bentoml.ai") as client:
            result = client.generate(
                # img=Path("https://assets.wfcdn.com/im/59302811/resize-h1500-w1500%5Ecompr-r85/1882/188248294/Window+Scenery+Green+Peaceful+Lake+Natural+Landscape+Photography+Pictures+Canvas+Print+Wall+Art.jpg"),
                img=Path(basename),
                txt="",
            )

        search_str = result
        print(search_str)
        st.write(search_str)

        search_str = remove_quotes(search_str)
        
        amazon_output = search_amazon(search_str)

        processed_lines = [append_tag_to_amazon_url(line) for line in amazon_output.split('\n')]
        output_str = '\n'.join(processed_lines)

        print(output_str)
        st.write(output_str)

    except Exception as e:
        st.error(f'An error occurred: {e}')