#!/usr/bin/env python3
"""
RateRight Construction Photo Analyzer

Analyze construction site photos to identify trade types, safety gear, equipment, and conditions.
Generates marketing insights and post caption suggestions.

Usage:
    python photo-analyzer.py /path/to/photo.jpg
    
Example:
    python photo-analyzer.py ./site-photos/formwork-crew.jpg
    python photo-analyzer.py https://example.com/construction-photo.jpg

Output:
    - Trade type identification
    - Safety equipment assessment
    - Equipment and tools identified
    - Site conditions evaluation
    - Marketing insights (e.g., "steel fixing crew needed")
    - Social media caption suggestions
"""

import sys
import json
import logging
from pathlib import Path
import base64
import requests

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 encode_image(image_path):
    """Encode image to base64 for API processing."""
    try:
        if image_path.startswith(('http://', 'https://')):
            # Download image from URL
            response = requests.get(image_path, timeout=30)
            response.raise_for_status()
            return base64.b64encode(response.content).decode('utf-8')
        else:
            # Read local image file
            with open(image_path, "rb") as image_file:
                return base64.b64encode(image_file.read()).decode('utf-8')
    except Exception as e:
        logger.error(f"Failed to encode image: {e}")
        return None

def analyze_construction_photo(image_path):
    """Analyze construction photo using OpenAI Vision 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)
    
    # Encode image
    base64_image = encode_image(image_path)
    if not base64_image:
        return None
    
    system_prompt = """You are a construction industry expert analyzing site photos for RateRight, 
    an Australian construction hiring marketplace. Provide detailed analysis for marketing purposes.
    
    Focus on identifying:
    1. Trade types and specializations visible
    2. Safety equipment and compliance
    3. Equipment, tools, and machinery
    4. Site conditions and project phase
    5. Workforce size and composition
    6. Quality standards and workmanship level
    
    Generate marketable insights about hiring needs and workforce requirements."""

    user_prompt = """Analyze this construction site photo and provide:

1. TRADE IDENTIFICATION
   - Primary trade(s) visible
   - Specialization level (apprentice, journeyman, expert)
   - Number of workers visible

2. SAFETY ASSESSMENT
   - PPE compliance (hard hats, hi-vis, steel caps, etc.)
   - Safety equipment present
   - Any safety concerns visible

3. EQUIPMENT & TOOLS
   - Major equipment visible
   - Hand tools and specialized gear
   - Equipment quality/condition

4. SITE CONDITIONS
   - Project type (residential, commercial, infrastructure)
   - Construction phase
   - Site organization and cleanliness
   - Weather conditions if apparent

5. MARKETABLE INSIGHTS
   - Hiring needs this photo suggests
   - Skill gaps or shortages evident
   - Equipment/supply needs
   - Project timeline implications

6. SOCIAL MEDIA CAPTIONS
   - 3 LinkedIn caption suggestions
   - 2 Instagram caption suggestions
   - 1 TikTok caption idea
   - Include relevant hashtags and emojis where appropriate

Format response with clear sections and bullet points. Be specific and actionable for marketing purposes."""

    try:
        response = client.chat.completions.create(
            model="gpt-4-vision-preview",
            messages=[
                {"role": "system", "content": system_prompt},
                {
                    "role": "user", 
                    "content": [
                        {"type": "text", "text": user_prompt},
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": f"data:image/jpeg;base64,{base64_image}"
                            }
                        }
                    ]
                }
            ],
            max_tokens=1500
        )
        
        content = response.choices[0].message.content
        logger.info(f"Successfully analyzed construction photo: {image_path}")
        return content
        
    except Exception as e:
        logger.error(f"OpenAI Vision API error: {e}")
        return None

def format_output(content, image_path):
    """Format the analysis for display."""
    from datetime import datetime
    
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    
    output = f"""# RateRight Construction Photo Analyzer
Analyzed on: {timestamp}
Image: {image_path}

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

"""
    return output

def main():
    """Main function to handle command line execution."""
    
    if len(sys.argv) < 2:
        print("Usage: python photo-analyzer.py /path/to/photo.jpg")
        print("Example: python photo-analyzer.py ./site-photos/formwork-crew.jpg")
        print("         python photo-analyzer.py https://example.com/photo.jpg")
        sys.exit(1)
    
    image_path = sys.argv[1]
    logger.info(f"Starting photo analysis for: {image_path}")
    
    # Validate image path
    if not image_path.startswith(('http://', 'https://')):
        if not Path(image_path).exists():
            print(f"Error: Image file not found: {image_path}")
            logger.error(f"Image file not found: {image_path}")
            sys.exit(1)
    
    # Analyze photo
    content = analyze_construction_photo(image_path)
    
    if content:
        formatted_output = format_output(content, image_path)
        print(formatted_output)
        logger.info("Photo analysis completed successfully")
    else:
        print("Failed to analyze photo. Check logs for details.")
        logger.error("Photo analysis failed")
        sys.exit(1)

if __name__ == "__main__":
    main()