#!/usr/bin/env python3
import requests
from PIL import Image, ImageDraw, ImageFont
import os
import random
from datetime import datetime, timedelta
import json

# Topics for rotation
TOPICS = ["SEO", "Social Media", "Digital Marketing", "AI", "Content Marketing", "Branding"]

# Pick a random topic that hasn't been used recently
state_file = "/home/mantapman/.hermes/profiles/atun/workspace/ig_story_state.json"
if os.path.exists(state_file):
    with open(state_file, 'r') as f:
        state = json.load(f)
    last_topic = state.get('last_topic', '')
else:
    state = {}
    last_topic = ''

# Select a random topic different from last one
available_topics = [t for t in TOPICS if t != last_topic]
if not available_topics:
    available_topics = TOPICS
selected_topic = random.choice(available_topics)

# Determine overlay color pattern (alternating black/white)
# Use date to ensure consistency
Today_date = datetime.now().strftime('%Y-%m-%d')
color_pattern = hash(Today_date) % 2  # 0 = start with black, 1 = start with white
overlay_color = "black" if color_pattern == 0 else "white"

print(f"Selected topic: {selected_topic}")
print(f"Overlay color pattern: {overlay_color}")

# Download Pexels background image
try:
    # Use a high-quality digital marketing image from Pexels
    image_url = "https://images.pexels.com/photos/3184418/pexels-photo-3184418.jpeg"
    response = requests.get(image_url)
    if response.status_code == 200:
        with open("/tmp/digital_marketing_bg.jpg", "wb") as f:
            f.write(response.content)
        print("Downloaded background image")
    else:
        # Fallback to another image
        image_url = "https://images.pexels.com/photos/1640772/pexels-photo-1640772.jpeg"
        response = requests.get(image_url)
        with open("/tmp/digital_marketing_bg.jpg", "wb") as f:
            f.write(response.content)
        print("Downloaded fallback background image")
except Exception as e:
    print(f"Error downloading image: {e}")
    # Create a simple gradient background as fallback
    img = Image.new('RGB', (1080, 1920), color='#FF6B35')
    img.save("/tmp/digital_marketing_bg.jpg")
    print("Created fallback gradient background")

# Load and process the background image
try:
    img = Image.open("/tmp/digital_marketing_bg.jpg")
    
    # Resize to Instagram Story dimensions (1080×1920)
    img = img.resize((1080, 1920), Image.Resampling.LANCZOS)
    
    # Create overlay pattern
    overlay = Image.new('RGBA', img.size)
    draw = ImageDraw.Draw(overlay)
    
    # Draw alternating rectangles for pattern
    for y in range(0, 1920, 40):  # 40px height strips
        if (y // 40) % 2 == color_pattern:
            color = (0, 0, 0, 179) if overlay_color == "black" else (255, 255, 255, 204)
            draw.rectangle([(0, y), (1080, y + 30)], fill=color)
    
    # Apply overlay
    img = Image.alpha_composite(img.convert('RGBA'), overlay)
    
    # Convert back to RGB for saving
    img = img.convert('RGB')
    
    # Prepare text
    draw = ImageDraw.Draw(img)
    
    # Load fonts
    bold_font_path = "/home/mantapman/.hermes/profiles/atun/workspace/fonts/Poppins-Bold.ttf"
    regular_font_path = "/home/mantapman/.hermes/profiles/atun/workspace/fonts/Poppins-Regular.ttf"
    
    # Try to load fonts, fallback to default if not available
    try:
        title_font = ImageFont.truetype(bold_font_path, 70)
    except:
        title_font = ImageFont.load_default()
        print("Using default font for title")
    
    try:
        body_font = ImageFont.truetype(regular_font_path, 43)
    except:
        body_font = ImageFont.load_default()
        print("Using default font for body")
    
    # Title text - centered
    title = selected_topic
    body = "Tingkatkan Bisnis Anda dengan Solusi Digital Marketing"
    cta = "KONSULTASI GRATIS SEKARANG!"
    
    # Get text sizes
    bbox_title = draw.textbbox((0, 0), title, font=title_font)
    title_width = bbox_title[2] - bbox_title[0]
    title_height = bbox_title[3] - bbox_title[1]
    
    bbox_body = draw.textbbox((0, 0), body, font=body_font)
    body_width = bbox_body[2] - bbox_body[0]
    body_height = bbox_body[3] - bbox_body[1]
    
    bbox_cta = draw.textbbox((0, 0), cta, font=title_font)
    cta_width = bbox_cta[2] - bbox_cta[0]
    cta_height = bbox_cta[3] - bbox_cta[1]
    
    # Center positions
    title_x = (1080 - title_width) // 2
    title_y = 400  # Top section
    
    body_x = (1080 - body_width) // 2
    body_y = 500  # Middle section
    
    cta_x = (1080 - cta_width) // 2
    cta_y = 650  # Bottom section
    
    # Draw text
    # Title - white text with shadow for contrast
    draw.text((cta_x + 2, cta_y + 2), cta, font=title_font, fill=(0, 0, 0))
    draw.text((cta_x, cta_y), cta, font=title_font, fill=(255, 255, 255))
    
    # Body text
    draw.text((body_x + 1, body_y + 1), body, font=body_font, fill=(0, 0, 0))
    draw.text((body_x, body_y), body, font=body_font, fill=(255, 255, 255))
    
    # Title
    draw.text((title_x + 1, title_y + 1), title, font=title_font, fill=(0, 0, 0))
    draw.text((title_x, title_y), title, font=title_font, fill=(255, 255, 255))
    
    # Load and resize StudioSoft logo
    try:
        # Try to download logo from studiosoft.id
        logo_url = "https://studiosoft.id/wp-content/uploads/2024/01/logo-studiosoft.png"
        logo_response = requests.get(logo_url)
        if logo_response.status_code == 200:
            logo_path = "/tmp/studiosoft_logo.png"
            with open(logo_path, "wb") as f:
                f.write(logo_response.content)
            logo = Image.open(logo_path)
            # Resize logo
            logo_width = 150
            logo_ratio = logo.width / logo.height
            logo_height = int(logo_width / logo_ratio)
            logo = logo.resize((logo_width, logo_height), Image.Resampling.LANCZOS)
            
            # Position logo at bottom center (100px from bottom)
            logo_x = (1080 - logo_width) // 2
            logo_y = 1920 - 100 - logo_height
            
            img.paste(logo, (logo_x, logo_y), logo if logo.mode == 'RGBA' else None)
    except Exception as e:
        print(f"Could not download logo: {e}")
        # Draw text logo as fallback
        footer_text = "www.studiosoft.id"
        bbox_footer = draw.textbbox((0, 0), footer_text, font=body_font)
        footer_width = bbox_footer[2] - bbox_footer[0]
        footer_x = (1080 - footer_width) // 2
        draw.text((footer_x + 1, 1920 - 80 + 1), footer_text, font=body_font, fill=(0, 0, 0))
        draw.text((footer_x, 1920 - 80), footer_text, font=body_font, fill=(255, 255, 255))
    
    # Save the image
    output_path = "/tmp/instagram_story.jpg"
    img.save(output_path, "JPEG", quality=95)
    print(f"Instagram story saved to: {output_path}")
    
    # Update state
    state.update({
        'last_topic': selected_topic,
        'overlay_color': overlay_color,
        'date': datetime.now().strftime('%Y-%m-%d'),
        'last_generated': datetime.now().isoformat()
    })
    
    with open(state_file, 'w') as f:
        json.dump(state, f, indent=2)
    
    print(f"State updated - Topic: {selected_topic}, Overlay: {overlay_color}")
    
except Exception as e:
    print(f"Error processing image: {e}")
    import traceback
    traceback.print_exc()