#!/usr/bin/env python3
"""
Fix articles to make them visible on homepage
"""

import weaviate

# Connect to Weaviate
client = weaviate.connect_to_local()
articles = client.collections.get("Articles")

# Get all articles
response = articles.query.fetch_objects(
    limit=10
)

print("Fixing articles for homepage visibility...")
updated = 0

for article in response.objects:
    props = article.properties
    needs_update = False
    updates = {}
    
    # Check for missing required fields
    if not props.get('city'):
        updates['city'] = 'Chicago'
        needs_update = True
    
    if not props.get('state'):
        updates['state'] = 'IL'
        needs_update = True
    
    if not props.get('image_url'):
        # Generate image based on violation category
        category = props.get('violation_category', 'general')
        if 'temperature' in category.lower():
            updates['image_url'] = '/assets/images/violations/temperature_1.jpg'
        elif 'hygiene' in category.lower():
            updates['image_url'] = '/assets/images/violations/handwashing_1.jpg'
        elif 'pest' in category.lower() or 'rodent' in category.lower():
            updates['image_url'] = '/assets/images/violations/rodent_1.jpg'
        else:
            updates['image_url'] = '/assets/images/violations/general_1.jpg'
        needs_update = True
    
    if not props.get('image_category'):
        updates['image_category'] = props.get('violation_category', 'general')
        needs_update = True
    
    if not props.get('establishment_name') and props.get('facility_name'):
        updates['establishment_name'] = props.get('facility_name')
        needs_update = True
    
    # Ensure published_date is set
    if not props.get('published_date'):
        updates['published_date'] = props.get('created_at', '2025-08-16T00:00:00Z')
        needs_update = True
    
    if needs_update:
        # Update article
        articles.data.update(
            uuid=article.uuid,
            properties=updates
        )
        
        print(f"✅ Updated article: {props.get('title', 'Unknown')[:50]}...")
        print(f"   Added fields: {', '.join(updates.keys())}")
        updated += 1
    else:
        print(f"✓ Article already complete: {props.get('title', 'Unknown')[:50]}...")

print(f"\nUpdated {updated} articles")
print("\nNow checking if articles are queryable...")

# Test the same query the homepage uses
test_query = """
{
    Get {
        Articles(
            limit: 6
            sort: [{path: ["published_date"], order: desc}]
        ) {
            title slug excerpt city state published_date image_url image_category establishment_name
        }
    }
}
"""

import json
import requests

response = requests.post(
    'http://localhost:8080/v1/graphql',
    json={'query': test_query},
    headers={'Content-Type': 'application/json'}
)

if response.status_code == 200:
    data = response.json()
    if 'data' in data and 'Get' in data['data'] and 'Articles' in data['data']['Get']:
        articles = data['data']['Get']['Articles']
        print(f"\n✅ Found {len(articles)} articles in homepage query")
        for article in articles:
            print(f"  - {article.get('title', 'No title')[:50]}...")
            print(f"    URL: /{article.get('slug', 'no-slug')}")
    else:
        print("❌ No articles found in query")
else:
    print(f"❌ Query failed: {response.status_code}")

client.close()