#!/usr/bin/env python3
"""
Etsy Social Marketing Content Generator

Generates platform-optimized social media content from Etsy listings.
Designed for RoyalStylesCreations niches: USMC, Military, Reformed Christian, Patriotic, Nature.

Usage:
    python3 generate_content.py <etsy-url> [--platform pinterest|instagram|facebook] [--all-platforms]
"""

import sys
import json
import re
from typing import Dict, List
from urllib.parse import urlparse

# Niche detection keywords
NICHE_KEYWORDS = {
    'USMC': ['usmc', 'marine', 'semper fi', 'devil dog', 'leatherneck', 'oorah'],
    'Military': ['military', 'veteran', 'army', 'navy', 'air force', 'service member'],
    'Reformed Christian': ['reformed', 'calvinist', 'heidelberg', 'westminster', 'covenant', 'five solas'],
    'Patriotic': ['patriotic', 'american', 'usa', 'america', 'flag', 'liberty', 'freedom'],
    'Nature': ['nature', 'mountain', 'hiking', 'outdoor', 'wilderness', 'forest', 'adventure']
}

# Hashtag libraries by niche
HASHTAGS = {
    'USMC': [
        '#USMC', '#Marines', '#SemperFi', '#DevilDog', '#MarineCorps',
        '#OohRah', '#LeatherneckNation', '#USMCVeteran', '#MarinePride',
        '#OnceAMarineAlwaysAMarine'
    ],
    'Military': [
        '#Military', '#Veteran', '#ArmedForces', '#SupportOurTroops',
        '#VeteranOwned', '#ProudVeteran', '#MilitaryLife', '#ServiceMember'
    ],
    'Reformed Christian': [
        '#Reformed', '#ReformedTheology', '#Calvinism', '#FiveSolas',
        '#HeidelbergCatechism', '#CovenantTheology', '#ReformedChristian',
        '#ChristianFaith', '#BiblicalTruth'
    ],
    'Patriotic': [
        '#Patriotic', '#AmericanPride', '#USA', '#FourthOfJuly',
        '#RedWhiteAndBlue', '#Freedom', '#Liberty', '#ProudAmerican',
        '#AmericanFlag', '#Americana'
    ],
    'Nature': [
        '#NatureLovers', '#MountainLife', '#HikingAdventures', '#Wilderness',
        '#OutdoorDecor', '#NatureArt', '#AdventureAwaits', '#ExploreMore',
        '#NaturePhotography', '#MountainView'
    ]
}

# Pinterest board mapping
PINTEREST_BOARDS = {
    'USMC': 'USMC Pride',
    'Military': 'Military Gifts',
    'Reformed Christian': 'Reformed Christian Art',
    'Patriotic': 'Patriotic Decor',
    'Nature': 'Nature Art'
}


class EtsySocialGenerator:
    def __init__(self, etsy_url: str):
        self.url = etsy_url
        self.listing_data = self._extract_from_url()
        self.niche = self._detect_niche()
    
    def _extract_from_url(self) -> Dict:
        """
        Extract listing data from Etsy URL.
        In production, this would scrape the listing page.
        For now, returns prompt for manual extraction.
        """
        return {
            'url': self.url,
            'title': '',
            'description': '',
            'price': '',
            'tags': [],
            'manual_extraction_needed': True,
            'extraction_guide': {
                'title': 'Copy full Etsy listing title',
                'description': 'Copy first paragraph of description',
                'price': 'Copy listing price',
                'tags': 'Copy all Etsy tags (comma-separated)',
                'niche': 'Identify: USMC, Military, Reformed Christian, Patriotic, or Nature'
            }
        }
    
    def _detect_niche(self) -> str:
        """Detect niche from title, description, and tags."""
        text = f"{self.listing_data.get('title', '')} {self.listing_data.get('description', '')} {' '.join(self.listing_data.get('tags', []))}".lower()
        
        scores = {}
        for niche, keywords in NICHE_KEYWORDS.items():
            score = sum(1 for kw in keywords if kw in text)
            if score > 0:
                scores[niche] = score
        
        if scores:
            return max(scores, key=scores.get)
        return 'General'
    
    def generate_pinterest(self) -> Dict:
        """Generate Pinterest pin description and metadata."""
        title = self.listing_data.get('title', 'Product')
        description = self.listing_data.get('description', '')
        niche = self.niche
        
        # Build Pinterest description (500 char max)
        pin_desc_template = f"""{title}

Perfect for {self._get_target_audience()}. Instant digital download - ready to print or use right away!

✨ What you get:
• High-resolution SVG file
• Perfect for Cricut, Silhouette, and other cutting machines
• Multiple size options included
• Commercial use license

{self._get_occasion_hook()}

#DigitalDownload #SVGFile #{niche.replace(' ', '')}"""
        
        return {
            'platform': 'Pinterest',
            'description': pin_desc_template[:500],
            'hashtags': self._get_hashtags('pinterest'),
            'board': PINTEREST_BOARDS.get(niche, 'General'),
            'niche': niche
        }
    
    def generate_instagram(self, format_type='feed') -> Dict:
        """Generate Instagram caption and metadata."""
        title = self.listing_data.get('title', 'Product')
        
        # Hook-driven caption
        hook = self._get_instagram_hook()
        caption = f"""{hook}

{self._get_benefit_statement()} Perfect for {self._get_target_audience()}! 🎯

Instant download - link in bio →

{' '.join(self._get_hashtags('instagram')[:10])}"""
        
        return {
            'platform': 'Instagram',
            'caption': caption,
            'hashtags': self._get_hashtags('instagram'),
            'content_type': format_type.capitalize(),
            'niche': self.niche
        }
    
    def generate_facebook(self) -> Dict:
        """Generate Facebook post."""
        title = self.listing_data.get('title', 'Product')
        
        post = f"""✨ {title}

Perfect for {self._get_target_audience()}!

{self._get_benefit_statement()}

👉 Shop now: {self.url}"""
        
        return {
            'platform': 'Facebook',
            'post': post,
            'link_preview': True,
            'niche': self.niche
        }
    
    def generate_all(self) -> Dict:
        """Generate content for all platforms."""
        return {
            'listing_url': self.url,
            'niche': self.niche,
            'pinterest': self.generate_pinterest(),
            'instagram': self.generate_instagram(),
            'facebook': self.generate_facebook()
        }
    
    def _get_hashtags(self, platform: str) -> List[str]:
        """Get platform-optimized hashtags."""
        base_tags = HASHTAGS.get(self.niche, [])
        common_tags = ['#DigitalDownload', '#SVGFile', '#EtsyShop', '#InstantDownload']
        
        all_tags = base_tags + common_tags
        
        if platform == 'pinterest':
            return all_tags[:15]  # Pinterest optimal: 10-15
        elif platform == 'instagram':
            return all_tags[:20]  # Instagram optimal: 10-30
        else:
            return all_tags[:10]  # Facebook: keep minimal
    
    def _get_target_audience(self) -> str:
        """Get target audience based on niche."""
        audiences = {
            'USMC': 'Marines, veterans, and proud families',
            'Military': 'service members, veterans, and military families',
            'Reformed Christian': 'Reformed Christians and homeschool families',
            'Patriotic': 'patriots and proud Americans',
            'Nature': 'outdoor enthusiasts and nature lovers'
        }
        return audiences.get(self.niche, 'gift-givers')
    
    def _get_benefit_statement(self) -> str:
        """Get niche-specific benefit statement."""
        benefits = {
            'USMC': 'Show your Marine Corps pride with this unique design!',
            'Military': 'Honor their service with meaningful art!',
            'Reformed Christian': 'Display your faith with beautiful, doctrinally sound art!',
            'Patriotic': 'Celebrate American pride and freedom!',
            'Nature': 'Bring the beauty of nature into your space!'
        }
        return benefits.get(self.niche, 'Perfect for gifts or personal use!')
    
    def _get_instagram_hook(self) -> str:
        """Get attention-grabbing Instagram hook."""
        hooks = {
            'USMC': '⚓ Semper Fi! ⚓',
            'Military': '🇺🇸 Honor their service',
            'Reformed Christian': '✝️ By grace alone',
            'Patriotic': '🇺🇸 Land of the free',
            'Nature': '🏔️ Adventure awaits'
        }
        return hooks.get(self.niche, '✨ New design!')
    
    def _get_occasion_hook(self) -> str:
        """Get timely occasion hook for Pinterest."""
        occasions = {
            'USMC': 'Perfect for Marine Corps Birthday (Nov 10), Veterans Day, or any day to honor a Marine!',
            'Military': 'Perfect for Veterans Day, Memorial Day, or honoring a service member!',
            'Reformed Christian': 'Perfect for Easter, Reformation Day, or everyday faith display!',
            'Patriotic': 'Perfect for 4th of July, Memorial Day, Veterans Day, or year-round pride!',
            'Nature': 'Perfect for Father\'s Day, outdoor lovers, or bringing nature indoors!'
        }
        return occasions.get(self.niche, 'Perfect for gifts or personal enjoyment!')


def main():
    if len(sys.argv) < 2:
        print(json.dumps({
            'error': 'Usage: python3 generate_content.py <etsy-url> [--platform pinterest|instagram|facebook] [--all-platforms]',
            'example': 'python3 generate_content.py https://www.etsy.com/listing/123456 --platform pinterest'
        }, indent=2))
        sys.exit(1)
    
    url = sys.argv[1]
    platform = None
    all_platforms = False
    
    # Parse arguments
    if '--all-platforms' in sys.argv:
        all_platforms = True
    elif '--platform' in sys.argv:
        idx = sys.argv.index('--platform')
        if idx + 1 < len(sys.argv):
            platform = sys.argv[idx + 1]
    
    generator = EtsySocialGenerator(url)
    
    # Generate content
    if all_platforms:
        result = generator.generate_all()
    elif platform == 'pinterest':
        result = generator.generate_pinterest()
    elif platform == 'instagram':
        result = generator.generate_instagram()
    elif platform == 'facebook':
        result = generator.generate_facebook()
    else:
        result = generator.generate_all()
    
    print(json.dumps(result, indent=2, ensure_ascii=False))


if __name__ == '__main__':
    main()
