import os
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont, ImageEnhance, ImageFilter
import requests
from io import BytesIO

BASE_DIR = Path(__file__).parent.parent
# We will store the base high-fidelity template images here
TEMPLATES_DIR = BASE_DIR / "Sunaiva" / "website_factory" / "static_templates"
TEMPLATES_DIR.mkdir(parents=True, exist_ok=True)

# Generated "Nano-Banana" payloads for outreach
OUTPUT_DIR = BASE_DIR / "Sunaiva" / "website_factory" / "entry_portals"
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)

# Fetch a beautiful base font if not present. Using Google Fonts Inter or Roboto.
FONT_DIR = BASE_DIR / "Sunaiva" / "fonts"
FONT_DIR.mkdir(parents=True, exist_ok=True)
FONT_PATH = FONT_DIR / "Inter-Bold.ttf"

def download_font_if_missing():
    if not FONT_PATH.exists():
        print("[Entry Portal] Downloading Inter-Bold font...")
        font_url = "https://github.com/google/fonts/raw/main/ofl/roboto/Roboto-Bold.ttf"
        try:
            r = requests.get(font_url)
            r.raise_for_status()
            with open(FONT_PATH, "wb") as f:
                f.write(r.content)
            print("[Entry Portal] Font downloaded.")
        except Exception as e:
            print(f"[Entry Portal] Failed to download font: {e}")

def create_placeholder_template(industry: str = "roofing"):
    """
    Creates a temporary solid gradient background to use if we don't have premium
    pre-rendered industry templates in the directory yet.
    """
    path = TEMPLATES_DIR / f"base_{industry}.jpg"
    if path.exists():
        return path
        
    print(f"[Entry Portal] Generating placeholder base template for {industry}...")
    # Create a nice dark gradient background representing a premium site
    img = Image.new('RGB', (1200, 630), color=(15, 23, 42))  # Slate 900
    draw = ImageDraw.Draw(img)
    
    # Draw a simple glassmorphism card in the center
    card_x, card_y, card_w, card_h = 200, 150, 800, 300
    draw.rounded_rectangle([card_x, card_y, card_x+card_w, card_y+card_h], radius=20, fill=(30, 41, 59, 200)) # Slate 800ish
    
    img.save(path)
    return path

def generate_nano_banana_portal(business_name: str, industry: str = "roofing") -> str:
    """
    Takes a pre-rendered high-fidelity SaaS/Website template for the given industry
    and dynamically burns the prospect's `business_name` directly into the hero text.
    Returns the file path of the generated "Nano-Banana" static payload.
    """
    download_font_if_missing()
    
    # Get or create the base template
    template_path = TEMPLATES_DIR / f"base_{industry}.jpg"
    if not template_path.exists():
        template_path = create_placeholder_template(industry)
        
    try:
        img = Image.open(template_path).convert("RGBA")
        # We will composite text over it
        txt_layer = Image.new("RGBA", img.size, (255, 255, 255, 0))
        draw = ImageDraw.Draw(txt_layer)
        
        # Load font
        try:
            font = ImageFont.truetype(str(FONT_PATH), size=64)
            sub_font = ImageFont.truetype(str(FONT_PATH), size=32)
        except OSError:
            # Fallback to default if download failed
            font = ImageFont.load_default()
            sub_font = ImageFont.load_default()

        # Text Setup
        headline = f"{business_name}"
        subheadline = f"The Next Generation of {industry.title()} Websites."
        
        # Calculate text width/height for centering
        # Use textbbox (Pillow 8.0+)
        bbox_head = draw.textbbox((0, 0), headline, font=font)
        head_w = bbox_head[2] - bbox_head[0]
        head_h = bbox_head[3] - bbox_head[1]
        
        bbox_sub = draw.textbbox((0, 0), subheadline, font=sub_font)
        sub_w = bbox_sub[2] - bbox_sub[0]
        
        img_w, img_h = img.size
        
        # Positions (Centering over the card we drew)
        head_x = (img_w - head_w) / 2
        head_y = (img_h / 2) - 40
        
        sub_x = (img_w - sub_w) / 2
        sub_y = head_y + head_h + 20
        
        # Draw Text with a slight drop shadow
        shadow_color = (0, 0, 0, 180)
        shadow_offset = 3
        
        draw.text((head_x + shadow_offset, head_y + shadow_offset), headline, font=font, fill=shadow_color)
        draw.text((sub_x + shadow_offset, sub_y + shadow_offset), subheadline, font=sub_font, fill=shadow_color)

        # Draw main text (Glowing cyan for business name, White for subheadline)
        draw.text((head_x, head_y), headline, font=font, fill=(0, 240, 255, 255))
        draw.text((sub_x, sub_y), subheadline, font=sub_font, fill=(200, 210, 220, 255))
        
        # Composite
        final_img = Image.alpha_composite(img, txt_layer)
        final_img = final_img.convert("RGB") # Remove alpha for JPEG output
        
        # Save payload
        safe_name = "".join([c for c in business_name if c.isalpha() or c.isdigit()]).lower()
        output_file = OUTPUT_DIR / f"{safe_name}_{industry}_payload.jpg"
        
        final_img.save(output_file, quality=90)
        print(f"[{business_name}] [NANO-BANANA] Generated: {output_file}")
        
        return str(output_file)
        
    except Exception as e:
        print(f"[Entry Portal] Error generating payload for {business_name}: {e}")
        return ""

if __name__ == "__main__":
    # Test the standalone script
    print("Testing Nano-Banana Outreach Hook Generator...")
    generate_nano_banana_portal("Prestige Law Group", "legal")
    generate_nano_banana_portal("Brisbane Elite Roofers", "roofing")
