#!/usr/bin/env python3
"""
RateRight LinkedIn Post Generator

Generate professional LinkedIn posts for the construction industry with multiple length variations.

Usage:
    python linkedin-generator.py "topic/theme"
    
Example:
    python linkedin-generator.py "steel fixing crew shortage in Sydney"
    python linkedin-generator.py "why formwork quality matters for project success"

Output:
    - Short post (50-100 words)
    - Medium post (150-200 words) 
    - Long post (250-300 words)
    - Each includes hashtags and call-to-action
"""

import sys
import json
import logging
from datetime import datetime
from pathlib import Path

try:
    import openai
except ImportError:
    print("OpenAI library not found. Installing...")
    import subprocess
    subprocess.check_call([sys.executable, "-m", "pip", "install", "openai"])
    import openai

# Setup logging
log_dir = Path("/home/ccuser/rateright-growth/rivet/memory")
log_dir.mkdir(exist_ok=True)
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler(log_dir / "content-engine.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

def load_openai_key():
    """Load OpenAI API key from secrets file."""
    try:
        secrets_path = "/root/.clawdbot/secrets.json"
        with open(secrets_path, 'r') as f:
            secrets = json.load(f)
            return secrets.get("openai_api_key") or secrets.get("OPENAI_API_KEY")
    except Exception as e:
        logger.error(f"Failed to load OpenAI key: {e}")
        return None

def generate_linkedin_posts(topic):
    """Generate LinkedIn posts using OpenAI API."""
    
    api_key = load_openai_key()
    if not api_key:
        logger.error("OpenAI API key not found")
        return None
    
    client = openai.OpenAI(api_key=api_key)
    
    system_prompt = """You are a content marketing expert for RateRight, a construction hiring marketplace in Australia. 
    Create professional LinkedIn posts that speak to contractors and construction professionals.
    
    Tone: Professional but relatable, contractor-to-contractor, data-driven
    Focus: Construction industry insights, hiring challenges, workforce trends
    Audience: Sydney-based contractors, project managers, construction business owners
    
    Include:
    - Industry-specific insights and data
    - Practical takeaways for contractors
    - Call-to-action related to hiring or workforce management
    - Relevant hashtags (max 8 per post)
    - Australian spelling and terminology"""

    user_prompt = f"""Create 3 LinkedIn posts about: {topic}

Requirements:
1. Short version (50-100 words) - Quick insight with 1-2 key points
2. Medium version (150-200 words) - Deeper analysis with 2-3 key points  
3. Long version (250-300 words) - Comprehensive insight with data/examples

Each post must:
- Start with a strong hook
- Include construction industry context
- Provide actionable insights
- End with a clear call-to-action
- Use 6-8 relevant hashtags
- Reference Sydney/Australia construction market when relevant

Topic: {topic}"""

    try:
        response = client.chat.completions.create(
            model="gpt-4",
            messages=[
                {"role": "system", "content": system_prompt},
                {"role": "user", "content": user_prompt}
            ],
            temperature=0.7,
            max_tokens=1500
        )
        
        content = response.choices[0].message.content
        logger.info(f"Successfully generated LinkedIn posts for topic: {topic}")
        return content
        
    except Exception as e:
        logger.error(f"OpenAI API error: {e}")
        return None

def format_output(content, topic):
    """Format the generated content for display."""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    output = f"""# RateRight LinkedIn Post Generator
Generated on: {timestamp}
Topic: {topic}

{'='*60}
{content}
{'='*60}

"""
    return output

def main():
    """Main function to handle command line execution."""
    
    if len(sys.argv) < 2:
        print("Usage: python linkedin-generator.py 'topic/theme'")
        print("Example: python linkedin-generator.py 'steel fixing crew shortage in Sydney'")
        sys.exit(1)
    
    topic = " ".join(sys.argv[1:])
    logger.info(f"Starting LinkedIn post generation for topic: {topic}")
    
    # Generate posts
    content = generate_linkedin_posts(topic)
    
    if content:
        formatted_output = format_output(content, topic)
        print(formatted_output)
        logger.info("LinkedIn posts generated successfully")
    else:
        print("Failed to generate LinkedIn posts. Check logs for details.")
        logger.error("Failed to generate LinkedIn posts")
        sys.exit(1)

if __name__ == "__main__":
    main()