#!/usr/bin/env python3
"""
RateRight LinkedIn Post Generator
Generates 3 LinkedIn post drafts per week for construction hiring marketplace
"""

import json
import random
from datetime import datetime, timedelta
from pathlib import Path

class LinkedInPostGenerator:
    def __init__(self):
        self.posts_dir = Path("/home/ccuser/rateright-growth/rivet/content/linkedin-drafts")
        self.posts_dir.mkdir(exist_ok=True)
        
        # Post templates following RateRight brand voice
        self.pain_point_templates = [
            {
                "hook": "Hired a sparkie who didn't show?",
                "body": "You're not alone. 40% of construction hires ghost on day one.\n\nOld way: Post job → Wait 3 days → Interview → Hire → No-show → Start over\n\nBetter way: RateRight workers have track records. You see who's reliable before you hire.\n\n$50 flat fee. No percentages. No BS.",
                "cta": "Need reliable workers? Post your job →"
            },
            {
                "hook": "Still paying 20% to labour hire?",
                "body": "Your worker earns $500/day. Agency takes $100. For what?\n\nA phone call?\n\nRateRight: Worker gets $500. You pay $50 once.\n\nThat's it. No ongoing fees. No percentages. No subscriptions.",
                "cta": "Stop getting ripped off. Try RateRight →"
            },
            {
                "hook": "Waiting 60 days to get paid?",
                "body": "Bricky from Liverpool waited 2 months for his last payment.\n\n60 days to get paid for work he did in December.\n\nRateRight: Get paid same day job's approved.\n\nBecause tradies have bills too. And rent. And families.",
                "cta": "Get paid fast. Join RateRight →"
            },
            {
                "hook": "Need 3 concreters by tomorrow?",
                "body": "Traditional labour hire: 'We'll get back to you in 48 hours'\n\nMeanwhile your concrete's setting and your client's losing it.\n\nRateRight: Post job → Get applications in minutes → Hire today → Work tomorrow\n\n$50 flat fee. Workers ready to go.",
                "cta": "Fill your job today →"
            }
        ]
        
        self.value_prop_templates = [
            {
                "hook": "$50 flat fee. That's the whole model.",
                "body": "Worker charges $600/day → Gets $600\nContractor pays $650 total → $600 to worker, $50 to us\n\nNo percentages.\nNo subscriptions.\nNo hidden fees.\n\nOne hire. One fee. Done.",
                "cta": "Post your first job →"
            },
            {
                "hook": "Workers keep 100%. Always.",
                "body": "Your rate is your rate.\n\nCharge $500/day? You get $500.\nCharge $750/day? You get $750.\n\nWe don't touch your money.\nWe don't take a percentage.\nWe don't 'optimize' your earnings.\n\n$50 flat fee paid by the contractor. That's it.",
                "cta": "Set your rate. Keep your money →"
            },
            {
                "hook": "Like Uber for construction. But fairer.",
                "body": "Uber takes 25-30% from drivers.\n\nWe take $50 flat. Whether it's a 1-day job or 6-month project.\n\nWorker does $15k job? Keeps $15k.\nContractor hires for 6 months? Still $50.\n\nSimple. Fair. How it should be.",
                "cta": "Try the fair way to hire →"
            }
        ]
        
        self.insight_templates = [
            {
                "hook": "Construction's biggest problem isn't skill shortage.",
                "body": "It's trust shortage.\n\nContractors don't trust workers will show up.\nWorkers don't trust they'll get paid.\n\nEveryone's been burned. So everyone's cautious.\n\nSolution: Transparent ratings. Verified track records. Fast payments.\n\nBuild trust, build projects.",
                "cta": "Hire trusted workers →"
            },
            {
                "hook": "Your labour hire agency is laughing.",
                "body": "Worker: $500/day\nAgency: $100/day (20%)\nYou: $600/day total\n\nFor making a phone call.\n\nIn 1995, that made sense. No internet. No smartphones.\n\nIt's 2025. There's a better way.",
                "cta": "Cut out the middleman →"
            },
            {
                "hook": "Sydney construction's dirty secret:",
                "body": "30% of workers are underpaid.\n40% of contractors overpay.\nEveryone's getting screwed.\n\nWhy? No transparency.\n\nWorkers don't know their real market rate.\nContractors don't know fair pricing.\n\nTime to fix that.",
                "cta": "See fair rates for your trade →"
            }
        ]
        
        # Industry stats and facts
        self.stats = [
            "40% of construction hires ghost on day one",
            "Average tradie waits 45 days to get paid",
            "Labour hire agencies take 15-25% of worker pay",
            "Sydney needs 15,000 more construction workers this year",
            "60% of contractors struggle to fill jobs on time",
            "Construction turnover is 2x higher than other industries"
        ]
        
        # Trades and locations
        self.trades = ["sparkies", "plumbers", "chippies", "brickies", "concreters", "steelfixers", "formworkers", "scaffolders"]
        self.suburbs = ["Campbelltown", "Liverpool", "Blacktown", "Parramatta", "Penrith", "Newcastle", "Wollongong"]
    
    def generate_post(self, post_type=None):
        """Generate a single LinkedIn post"""
        if post_type is None:
            post_type = random.choice(["pain", "value", "insight"])
        
        if post_type == "pain":
            template = random.choice(self.pain_point_templates)
        elif post_type == "value":
            template = random.choice(self.value_prop_templates)
        else:  # insight
            template = random.choice(self.insight_templates)
        
        # Add random variation
        post = template.copy()
        
        # Replace placeholders
        if "[trade]" in post["body"]:
            post["body"] = post["body"].replace("[trade]", random.choice(self.trades))
        if "[suburb]" in post["body"]:
            post["body"] = post["body"].replace("[suburb]", random.choice(self.suburbs))
        
        # Add stat occasionally
        if random.random() > 0.5 and post_type == "pain":
            post["body"] += f"\n\n📊 {random.choice(self.stats)}"
        
        # Format the final post
        formatted_post = f"{post['hook']}\n\n{post['body']}\n\n{post['cta']}"
        
        return formatted_post
    
    def generate_weekly_posts(self):
        """Generate 3 posts for the week"""
        posts = []
        week_types = ["pain", "value", "insight"]  # One of each type
        
        for i, post_type in enumerate(week_types):
            post = self.generate_post(post_type)
            posts.append({
                "type": post_type,
                "content": post,
                "date": datetime.now() + timedelta(days=i*2),  # Spread across week
                "word_count": len(post.split())
            })
        
        return posts
    
    def save_posts(self, posts):
        """Save posts to files with metadata"""
        timestamp = datetime.now().strftime("%Y-%m-%d")
        
        for i, post in enumerate(posts, 1):
            filename = f"{timestamp}-post-{i}.md"
            filepath = self.posts_dir / filename
            
            content = f"""# LinkedIn Post Draft {i}
**Type:** {post['type'].title()}
**Date:** {post['date'].strftime('%Y-%m-%d %H:%M')}
**Word Count:** {post['word_count']}

---

{post['content']}

---

**Notes:**
- Keep under 200 words ✓
- Direct, worker-focused tone ✓
- Clear CTA ✓
- No corporate speak ✓
"""
            
            with open(filepath, 'w') as f:
                f.write(content)
            
            print(f"✓ Saved: {filename} ({post['word_count']} words)")
    
    def run(self):
        """Generate and save weekly posts"""
        print("🎯 Generating 3 LinkedIn posts for RateRight...")
        print("=" * 50)
        
        posts = self.generate_weekly_posts()
        self.save_posts(posts)
        
        print("=" * 50)
        print(f"✅ Generated 3 posts in {self.posts_dir}")
        print("\nPost summary:")
        for i, post in enumerate(posts, 1):
            print(f"  {i}. {post['type'].title()} post ({post['word_count']} words)")

if __name__ == "__main__":
    generator = LinkedInPostGenerator()
    generator.run()