import gradio as gr
import http.client
from PIL import Image, ImageDraw, ImageFont
import urllib.parse
import json

# RapidAPI credentials and host
API_KEY = "2e427e3d07mshba1bdb10cb6eb30p12d12fjsn215dd7746115"  # Replace with your actual API key
API_HOST = "horoscopes-ai.p.rapidapi.com"

# Function to fetch and parse horoscope based on sign and period
def get_horoscope(sign, period="today"):
    conn = http.client.HTTPSConnection(API_HOST)
    
    headers = {
        'x-rapidapi-key': API_KEY,
        'x-rapidapi-host': API_HOST
    }
    
    # Construct the endpoint with the selected sign and period
    endpoint = f"/get_horoscope_en/{sign}/{period}/general"
    
    # Make the GET request to the endpoint
    conn.request("GET", endpoint, headers=headers)
    res = conn.getresponse()
    data = res.read().decode("utf-8")
    
    # Parse the JSON response and extract the horoscope text
    try:
        response_data = json.loads(data)
        horoscope_text = response_data.get("general", ["No horoscope available"])[0]
    except json.JSONDecodeError:
        horoscope_text = "Error: Unable to parse horoscope data."
    
    return horoscope_text

# Function to generate an image from the horoscope text
def generate_horoscope_image(text):
    # Set image size and background color
    width, height = 800, 400
    background_color = "lightblue"
    
    # Create a blank image with background color
    image = Image.new("RGB", (width, height), color=background_color)
    draw = ImageDraw.Draw(image)
    
    # Set font and text color
    try:
        font = ImageFont.truetype("arial.ttf", size=20)
    except IOError:
        font = ImageFont.load_default()
    
    text_color = "black"
    padding = 20
    
    # Wrap text to fit within the image width
    lines = []
    words = text.split()
    while words:
        line = ''
        while words and (draw.textlength(line + words[0], font=font) <= width - padding * 2):
            line += (words.pop(0) + ' ')
        lines.append(line)
    
    # Calculate vertical position for centered text
    total_text_height = sum([draw.textbbox((0, 0), line, font=font)[3] - draw.textbbox((0, 0), line, font=font)[1] for line in lines])
    y_text = (height - total_text_height) // 2
    
    # Draw each line of text
    for line in lines:
        text_width = draw.textlength(line, font=font)
        x_text = (width - text_width) // 2  # Center align
        draw.text((x_text, y_text), line, font=font, fill=text_color)
        y_text += draw.textbbox((0, 0), line, font=font)[3] - draw.textbbox((0, 0), line, font=font)[1]
    
    # Save image to a temporary path
    image_path = "/tmp/horoscope_image.png"
    image.save(image_path)
    return image_path

# Gradio Interface Setup
with gr.Blocks() as demo:
    gr.Markdown("<center><h1>Daily Horoscope by Enemy AI</h1></center>")
    gr.Markdown("Select your zodiac sign and period to receive your personalized horoscope.")
    
    # Input dropdowns for sign and period
    sign_dropdown = gr.Dropdown(label="Select Your Zodiac Sign", choices=[
        "aries", "taurus", "gemini", "cancer", "leo", "virgo", 
        "libra", "scorpio", "sagittarius", "capricorn", "aquarius", "pisces"
    ])
    period_dropdown = gr.Dropdown(label="Select Period", choices=["today", "tomorrow", "yesterday"], value="today")
    
    # Textbox to display the horoscope
    horoscope_output = gr.Textbox(label="Your Horoscope")
    
    # Link to share on Twitter
    twitter_link = gr.HTML()
    
    # Image output for download
    horoscope_image = gr.Image(label="Downloadable Horoscope Image")
    
    # Button to trigger the API call
    btn_get_horoscope = gr.Button("Get Horoscope")
    
    # Define the button click event
    def on_click(sign, period):
        horoscope_text = get_horoscope(sign, period)
        
        # Prepare Twitter share link
        share_text = f"Here's my horoscope for {sign.capitalize()} on {period.capitalize()}:\n{horoscope_text}"
        encoded_text = urllib.parse.quote(share_text)
        twitter_share_url = f"https://twitter.com/intent/tweet?text={encoded_text}"
        twitter_button_html = f'<a href="{twitter_share_url}" target="_blank" style="color: white; background-color: #1DA1F2; padding: 10px; border-radius: 5px; text-decoration: none;">Share on Twitter</a>'
        
        # Generate horoscope image for download
        image_path = generate_horoscope_image(horoscope_text)
        
        return horoscope_text, twitter_button_html, image_path
    
    # Set up Gradio click action
    btn_get_horoscope.click(fn=on_click, inputs=[sign_dropdown, period_dropdown], outputs=[horoscope_output, twitter_link, horoscope_image])

if __name__ == "__main__":
    demo.launch(server_name="0.0.0.0")