#!/usr/bin/env python3
"""
Pinterest Posting Automation via Publer API
Posts Etsy listing images to Pinterest with SEO descriptions.

Usage:
    python3 post-to-pinterest.py status          # Show queue status
    python3 post-to-pinterest.py dry-run         # Test without posting
    python3 post-to-pinterest.py post-next       # Post next in queue
    python3 post-to-pinterest.py post --id ID    # Post specific listing
"""

import argparse
import json
import os
import sys
import requests
from datetime import datetime
from pathlib import Path

# Paths
SCRIPT_DIR = Path(__file__).parent.parent
LISTINGS_FILE = SCRIPT_DIR / "etsy-listing-urls.json"
QUEUE_FILE = SCRIPT_DIR / "pin-queue.json"
LOG_FILE = SCRIPT_DIR / "posting-log.json"

# Publer API Configuration
PUBLER_API_BASE = "https://app.publer.com/api/v1"
PUBLER_API_KEY = os.getenv("PUBLER_API_KEY", "")
PUBLER_WORKSPACE_ID = os.getenv("PUBLER_WORKSPACE_ID", "")
PINTEREST_ACCOUNT_ID = os.getenv("PINTEREST_ACCOUNT_ID", "")

# Validate credentials are set
if not all([PUBLER_API_KEY, PUBLER_WORKSPACE_ID, PINTEREST_ACCOUNT_ID]):
    print("ERROR: Missing required credentials. Set PUBLER_API_KEY, PUBLER_WORKSPACE_ID, PINTEREST_ACCOUNT_ID in .env file")
    sys.exit(1)

# Pinterest Board IDs
BOARD_IDS = {
    "Military": "1082552897870101585",           # USMC & Marine Corps SVGs
    "Patriotic": "1082552897870101587",          # Patriotic & American Designs
    "Reformed SVGs": "1082552897870101588",      # Reformed Christian Art
    "Easter SVGs": "1082552897870101588",        # Reformed Christian Art
    "Nature/Animals/Insects": "1082552897870101593"  # Nature & Outdoor SVGs
}

# SEO Templates by category
TEMPLATES = {
    "Military": {
        "hashtags": "#MilitarySVG #USMC #MarineCorps #VeteranGift #MilitaryFamily #CricutProjects #SVGFiles",
    },
    "Patriotic": {
        "hashtags": "#PatrioticSVG #USA #AmericanFlag #4thOfJuly #CricutProjects #SVGFiles #PatrioticDecor",
    },
    "Reformed SVGs": {
        "hashtags": "#ReformedTheology #ChristianArt #ChurchDecor #FaithSVG #CricutProjects #ScriptureArt",
    },
    "Easter SVGs": {
        "hashtags": "#EasterSVG #ChristianEaster #HeIsRisen #ChurchDecor #CricutProjects #FaithArt",
    },
    "Nature/Animals/Insects": {
        "hashtags": "#NatureSVG #WildlifeArt #OutdoorDecor #HuntingSVG #CricutProjects #CabinDecor",
    }
}

def load_json(filepath):
    """Load JSON file"""
    with open(filepath) as f:
        return json.load(f)

def save_json(filepath, data):
    """Save JSON file"""
    with open(filepath, 'w') as f:
        json.dump(data, f, indent=2)

def get_listing_by_id(listing_id, listings_data):
    """Find listing by ID"""
    for listing in listings_data["listings"]:
        if listing["id"] == listing_id:
            return listing
    return None

def generate_pin_description(listing):
    """Generate SEO-optimized Pinterest description"""
    category = listing.get("category", "Patriotic")
    template = TEMPLATES.get(category, TEMPLATES["Patriotic"])
    
    description = f"""✨ {listing['title']} ✨

Perfect for Cricut, Silhouette, laser cutters & vinyl cutting machines!

🎨 Instant digital download includes:
• SVG file (vector, scalable)
• PNG file (high resolution)  
• Multiple formats

💡 Create: T-shirts, tumblers, wall art, car decals & more!

🛒 Shop now: {listing['url']}

{template['hashtags']}"""
    
    return description

def find_image_for_listing(listing_id):
    """Find the mockup image for a listing"""
    upload_ready = Path.home() / "Documents" / "Etsy Designs" / "03-Upload-Ready"
    
    for folder in upload_ready.iterdir():
        if folder.is_dir():
            # Look for mockup images
            for img in folder.glob("*-bag.jpg"):
                return str(img)
            for img in folder.glob("*-shirt.jpg"):
                return str(img)
            for img in folder.glob("*.jpg"):
                if not img.name.startswith("."):
                    return str(img)
    return None

def upload_media_to_publer(image_path):
    """Upload image to Publer and return media ID"""
    url = f"{PUBLER_API_BASE}/media/upload"
    headers = {
        "Authorization": f"Bearer-API {PUBLER_API_KEY}",
        "Publer-Workspace-Id": PUBLER_WORKSPACE_ID
    }
    
    with open(image_path, 'rb') as f:
        files = {'file': (os.path.basename(image_path), f, 'image/jpeg')}
        response = requests.post(url, headers=headers, files=files)
    
    if response.status_code == 200:
        data = response.json()
        return data.get('id')
    else:
        print(f"Media upload failed: {response.status_code} - {response.text}")
        return None

def post_to_pinterest(listing, image_path, dry_run=False):
    """Post to Pinterest via Publer API"""
    category = listing.get("category", "Patriotic")
    board_id = BOARD_IDS.get(category, BOARD_IDS["Patriotic"])
    description = generate_pin_description(listing)
    title = listing["title"][:100]  # Pinterest title limit
    
    if dry_run:
        print(f"\n[DRY RUN] Would post:")
        print(f"  Title: {title}")
        print(f"  Board ID: {board_id}")
        print(f"  Image: {image_path}")
        print(f"  Link: {listing['url']}")
        print(f"  Description preview: {description[:150]}...")
        return {"success": True, "dry_run": True}
    
    # For external image URL, we can use the image directly
    # First, let's try with an external URL approach
    
    url = f"{PUBLER_API_BASE}/posts/schedule/publish"
    headers = {
        "Authorization": f"Bearer-API {PUBLER_API_KEY}",
        "Publer-Workspace-Id": PUBLER_WORKSPACE_ID,
        "Content-Type": "application/json"
    }
    
    # Upload image first
    print(f"  Uploading image...")
    media_id = upload_media_to_publer(image_path)
    
    if not media_id:
        # Try with external URL if upload fails
        print(f"  Upload failed, trying external URL method...")
        payload = {
            "bulk": {
                "state": "scheduled",
                "posts": [{
                    "networks": {
                        "pinterest": {
                            "type": "photo",
                            "text": description,
                            "title": title,
                            "url": listing["url"],
                            "media": [{
                                "id": "external-0",
                                "type": "photo",
                                "path": f"file://{image_path}",
                                "thumbnail": f"file://{image_path}"
                            }]
                        }
                    },
                    "accounts": [{
                        "id": PINTEREST_ACCOUNT_ID,
                        "album_id": board_id
                    }]
                }]
            }
        }
    else:
        print(f"  Media uploaded: {media_id}")
        payload = {
            "bulk": {
                "state": "scheduled",
                "posts": [{
                    "networks": {
                        "pinterest": {
                            "type": "photo",
                            "text": description,
                            "title": title,
                            "url": listing["url"],
                            "media": [{
                                "id": media_id,
                                "type": "photo"
                            }]
                        }
                    },
                    "accounts": [{
                        "id": PINTEREST_ACCOUNT_ID,
                        "album_id": board_id
                    }]
                }]
            }
        }
    
    print(f"  Posting to Pinterest...")
    response = requests.post(url, headers=headers, json=payload)
    
    if response.status_code in [200, 201, 202]:
        data = response.json()
        job_id = data.get("job_id")
        print(f"  Job submitted: {job_id}")
        return {"success": True, "job_id": job_id, "response": data}
    else:
        print(f"  Post failed: {response.status_code}")
        print(f"  Response: {response.text}")
        return {"success": False, "error": response.text}

def post_next(dry_run=False):
    """Post the next item in the queue"""
    queue = load_json(QUEUE_FILE)
    listings = load_json(LISTINGS_FILE)
    log = load_json(LOG_FILE)
    
    # Find next pending item
    next_item = None
    next_index = None
    for i, item in enumerate(queue["queue"]):
        if item["status"] == "pending":
            next_item = item
            next_index = i
            break
    
    if not next_item:
        print("✅ No pending items in queue!")
        return
    
    listing = get_listing_by_id(next_item["listingId"], listings)
    if not listing:
        print(f"❌ Listing {next_item['listingId']} not found!")
        return
    
    # Find image
    image_path = find_image_for_listing(listing["id"])
    if not image_path:
        print(f"❌ No image found for listing {listing['id']}")
        return
    
    print(f"\n📌 Posting: {listing['title'][:60]}...")
    print(f"   Category: {listing['category']}")
    print(f"   URL: {listing['url']}")
    print(f"   Image: {os.path.basename(image_path)}")
    
    # Post
    result = post_to_pinterest(listing, image_path, dry_run)
    
    # Update queue and log
    if result.get("success"):
        status = "dry-run" if dry_run else "posted"
        queue["queue"][next_index]["status"] = status
        queue["queue"][next_index]["postedAt"] = datetime.now().isoformat()
        if result.get("job_id"):
            queue["queue"][next_index]["jobId"] = result["job_id"]
        queue["nextIndex"] = next_index + 1
        queue["lastUpdated"] = datetime.now().isoformat()
        
        log["posts"].append({
            "listingId": listing["id"],
            "title": listing["title"],
            "category": listing["category"],
            "postedAt": datetime.now().isoformat(),
            "dryRun": dry_run,
            "jobId": result.get("job_id")
        })
        if not dry_run:
            log["totalPosted"] += 1
        
        save_json(QUEUE_FILE, queue)
        save_json(LOG_FILE, log)
        
        print(f"\n✅ {'[DRY RUN] ' if dry_run else ''}Success!")
    else:
        print(f"\n❌ Failed: {result.get('error', 'Unknown error')}")

def show_status():
    """Show queue status"""
    queue = load_json(QUEUE_FILE)
    log = load_json(LOG_FILE)
    
    pending = len([q for q in queue["queue"] if q["status"] == "pending"])
    posted = len([q for q in queue["queue"] if q["status"] == "posted"])
    
    print(f"\n📊 Pinterest Posting Status")
    print(f"   Total in queue: {len(queue['queue'])}")
    print(f"   Pending: {pending}")
    print(f"   Posted: {posted}")
    print(f"   Next index: {queue['nextIndex']}")
    print(f"\n   Total posts logged: {log['totalPosted']}")

def main():
    parser = argparse.ArgumentParser(description="Pinterest posting via Publer API")
    parser.add_argument("command", choices=["post-next", "status", "dry-run"],
                       help="Command to run")
    parser.add_argument("--id", help="Specific listing ID to post")
    
    args = parser.parse_args()
    
    if args.command == "post-next":
        post_next(dry_run=False)
    elif args.command == "dry-run":
        post_next(dry_run=True)
    elif args.command == "status":
        show_status()

if __name__ == "__main__":
    main()
