#!/usr/bin/env python3
"""
H3R7Tech - POD Automation Script
Upload designs to Redbubble, TeeSpring, or Spreadshop
"""

import os
import json
import time
import random
from datetime import datetime

# Configuration
CONFIG = {
    "platform": "redbubble",  # redbubble, teespring, spreadshop
    "products": [
        {"name": "T-shirt", "base_price": 25.00, "cost": 12.00},
        {"name": "Mug", "base_price": 15.00, "cost": 5.00},
        {"name": "Poster", "base_price": 20.00, "cost": 4.00},
        {"name": "Sticker", "base_price": 8.00, "cost": 1.50},
        {"name": "Hoodie", "base_price": 45.00, "cost": 20.00},
    ],
    "design_folder": "./designs",
    "tags": ["h3r7tech", "tech", "coding", "developer", "python"],
    "title_prefix": "H3R7Tech - ",
    "description": "Official H3R7Tech merchandise. High quality products.",
}

def load_designs(folder):
    """Load all design files from folder"""
    designs = []
    if not os.path.exists(folder):
        os.makedirs(folder)
        print(f"⚠️ Created folder: {folder}")
        print(f"   Add your designs (.png, .jpg) and run again")
        return designs
    
    for f in os.listdir(folder):
        if f.lower().endswith(('.png', '.jpg', '.jpeg', '.svg')):
            designs.append({
                "filename": f,
                "path": os.path.join(folder, f),
                "name": f.replace('.png', '').replace('.jpg', '').replace('.jpeg', '').replace('_', ' ').replace('-', ' ').title()
            })
    
    return designs

def calculate_prices(product, markup=2.0):
    """Calculate selling price based on cost"""
    cost = product["cost"]
    price = round(cost * markup, 2)
    margin = round(price - cost, 2)
    return {
        "product": product["name"],
        "cost": cost,
        "price": price,
        "margin": margin,
        "margin_pct": round((margin / price) * 100, 1)
    }

def generate_product_data(design, product):
    """Generate product data for upload"""
    title = f"{CONFIG['title_prefix']}{design['name']} - {product['name']}"
    tags = CONFIG['tags'] + [design['name'].lower().replace(' ', ''), product['name'].lower()]
    
    return {
        "title": title,
        "description": f"{CONFIG['description']}\n\nDesign: {design['name']}\nProduct: {product['name']}\n\nTags: {', '.join(tags)}",
        "tags": tags[:15],  # Most platforms limit tags
        "price": calculate_prices(product),
        "design": design,
        "product_type": product["name"]
    }

def create_upload_summary(designs, products):
    """Create summary of what would be uploaded"""
    print("\n" + "="*50)
    print("📦 POD UPLOAD SUMMARY")
    print("="*50)
    print(f"Platform: {CONFIG['platform'].upper()}")
    print(f"Designs: {len(designs)}")
    print(f"Products: {len(products)}")
    print(f"Total items to create: {len(designs) * len(products)}")
    print()
    
    total_potential_revenue = 0
    for design in designs:
        print(f"📝 {design['name']}")
        for product in products:
            pricing = calculate_prices(product)
            print(f"   → {product['name']}: {pricing['price']}€ (marge: {pricing['margin']}€)")
            total_potential_revenue += pricing['price']
    
    print()
    print(f"💰 Revenu potentiel total: {total_potential_revenue}€")
    print("="*50)
    
    return {
        "designs": len(designs),
        "products": len(products),
        "total_items": len(designs) * len(products),
        "potential_revenue": total_potential_revenue
    }

def export_for_upload(designs, products, output_file="pod_upload_data.json"):
    """Export data for manual upload or automation"""
    data = {
        "generated": datetime.now().isoformat(),
        "platform": CONFIG["platform"],
        "items": []
    }
    
    for design in designs:
        for product in products:
            item = generate_product_data(design, product)
            data["items"].append(item)
    
    with open(output_file, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    
    print(f"\n✅ Data exported to: {output_file}")
    print(f"   Ready for upload or manual process automation")

def create_mockup_description():
    """Generate mockup prompts for AI image generation"""
    prompts = []
    designs = load_designs(CONFIG["design_folder"])
    
    for design in designs:
        for product in CONFIG["products"]:
            prompt = f"""Create a product mockup for {product['name']}:
- Design: {design['name']}
- Product: {product['name']}
- Style: Professional, clean, on white background
- Include: Front view of {product['name']} showing the design centered
- Quality: High resolution, photorealistic"""
            prompts.append({
                "design": design["name"],
                "product": product["name"],
                "prompt": prompt
            })
    
    with open("mockup_prompts.json", "w") as f:
        json.dump(prompts, f, indent=2)
    
    print(f"\n✅ Created {len(prompts)} mockup prompts in mockup_prompts.json")
    print("   Use these with Midjourney, DALL-E, or Stable Diffusion")

def main():
    print("🎨 H3R7Tech POD Automation")
    print("="*40)
    
    # Load designs
    designs = load_designs(CONFIG["design_folder"])
    
    if not designs:
        print("❌ No designs found!")
        print(f"   Add designs to: {CONFIG['design_folder']}/")
        return
    
    print(f"✅ Found {len(designs)} designs")
    
    # Generate summary
    summary = create_upload_summary(designs, CONFIG["products"])
    
    # Export data
    export_for_upload(designs, CONFIG["products"])
    
    # Generate mockup prompts
    create_mockup_description()
    
    print("\n📋 NEXT STEPS:")
    print("1. Review pod_upload_data.json")
    print("2. Generate mockups using AI (mockup_prompts.json)")
    print("3. Upload to platform manually OR use browser automation")
    print("4. Monitor sales and adjust pricing")

if __name__ == "__main__":
    main()
