#!/usr/bin/env python3
"""
Test article generation with Claude Haiku
"""

import os
import json
import sys
from datetime import datetime
from anthropic import Anthropic
from dotenv import load_dotenv

# Load environment variables
load_dotenv('/home/chris/.env')

# Test data - a real inspection record
test_inspection = {
    'establishment_name': 'SUBWAY',
    'address': '6500 N WESTERN AVE',
    'city': 'Chicago',
    'state': 'IL',
    'zip_code': '60645',
    'inspection_date': '2024-03-15',
    'inspection_id': '2024-test-001',
    'results': 'Fail',
    'violations': '32. FOOD AND NON-FOOD CONTACT SURFACES PROPERLY DESIGNED, CONSTRUCTED AND MAINTAINED - Comments: OBSERVED THE FOLLOWING AREAS WITH EXCESSIVE DUST ACCUMULATION: CEILING VENTS THROUGHOUT THE FACILITY. INSTRUCTED TO DETAIL CLEAN AND MAINTAIN. | 35. WALLS, CEILINGS, ATTACHED EQUIPMENT CONSTRUCTED PER CODE: GOOD REPAIR, SURFACES CLEAN AND DUST-LESS CLEANING METHODS - Comments: OBSERVED WALLS BEHIND THE 3-COMPARTMENT SINK AND PREP AREAS WITH FOOD DEBRIS AND GREASE ACCUMULATION. MUST CLEAN AND MAINTAIN.',
    'risk_level': 'Risk 1 (High)',
    'facility_type': 'Restaurant'
}

def test_haiku_article_generation():
    """Test generating an article with Claude Haiku"""
    
    client = Anthropic(api_key=os.getenv('ANTHROPIC_API_KEY'))
    
    # Build the prompt
    prompt = f"""You are a professional food safety journalist writing for CleanKitchens.org. Write a factual, neutral news article about this restaurant health inspection.

CRITICAL SAFETY RULES:
- Use ONLY the provided inspection data
- NO speculation or fabricated information
- Use neutral language: "received citations for", "violations found"
- NEVER say "was closed" or "shut down"
- Include educational angle

INSPECTION DATA:
Restaurant: {test_inspection['establishment_name']}
Address: {test_inspection['address']}, {test_inspection['city']}, {test_inspection['state']} {test_inspection['zip_code']}
Inspection Date: {test_inspection['inspection_date']}
Results: {test_inspection['results']}
Risk Level: {test_inspection['risk_level']}
Violations: {test_inspection['violations']}

Write a complete article and format your response EXACTLY as JSON with no other text:
{{
    "title": "headline here (60-80 chars)",
    "content": "full article content in HTML with <p> tags",
    "excerpt": "brief summary (150 chars)",
    "meta_description": "SEO description (160 chars)",
    "tags": ["tag1", "tag2", "tag3"]
}}"""

    print("📝 Testing article generation with Claude Haiku...")
    print(f"Restaurant: {test_inspection['establishment_name']}")
    print(f"Date: {test_inspection['inspection_date']}")
    print(f"Result: {test_inspection['results']}")
    print("\n" + "="*60)
    
    try:
        # Call Claude Haiku
        response = client.messages.create(
            model="claude-3-haiku-20240307",
            max_tokens=2000,
            temperature=0.3,
            messages=[{
                "role": "user",
                "content": prompt
            }]
        )
        
        # Get the response text
        response_text = response.content[0].text
        print("\n🤖 Claude Haiku Response:")
        print("-"*60)
        print(response_text)
        print("-"*60)
        
        # Try to parse as JSON
        print("\n📊 Parsing JSON...")
        try:
            # Find JSON in response
            start = response_text.find('{')
            end = response_text.rfind('}') + 1
            
            if start == -1 or end == 0:
                print("❌ No JSON found in response")
                return False
                
            json_str = response_text[start:end]
            article_data = json.loads(json_str)
            
            print("✅ Successfully parsed JSON!")
            print(f"\nTitle: {article_data.get('title', 'No title')}")
            print(f"Excerpt: {article_data.get('excerpt', 'No excerpt')}")
            print(f"Tags: {', '.join(article_data.get('tags', []))}")
            print(f"Content length: {len(article_data.get('content', ''))} characters")
            
            # Save to file for review
            output_file = '/var/www/twin-digital-media/public_html/_sites/cleankitchens/production/scripts/test_article_output.json'
            with open(output_file, 'w') as f:
                json.dump(article_data, f, indent=2)
            print(f"\n💾 Saved to: {output_file}")
            
            return True
            
        except json.JSONDecodeError as e:
            print(f"❌ JSON parsing failed: {e}")
            print(f"Attempted to parse: {json_str[:200]}...")
            return False
            
    except Exception as e:
        print(f"❌ API call failed: {e}")
        return False

def test_multiple_attempts():
    """Test multiple article generation attempts to check success rate"""
    
    print("\n🔄 Testing 5 article generation attempts...")
    print("="*60)
    
    successes = 0
    failures = 0
    
    for i in range(5):
        print(f"\n📝 Attempt {i+1}/5:")
        if test_haiku_article_generation():
            successes += 1
        else:
            failures += 1
        print("-"*60)
    
    print(f"\n📊 Results:")
    print(f"Successes: {successes}/5 ({successes*20}%)")
    print(f"Failures: {failures}/5 ({failures*20}%)")
    
    if successes == 0:
        print("\n⚠️  All attempts failed - there may be a prompt or parsing issue")
    elif successes < 3:
        print("\n⚠️  Low success rate - prompt may need adjustment")
    else:
        print("\n✅ Good success rate!")

if __name__ == "__main__":
    # Test single generation
    # test_haiku_article_generation()
    
    # Test multiple attempts
    test_multiple_attempts()