#!/usr/bin/env python3
"""
Fix missing slugs for articles
"""

import weaviate
import re
from datetime import datetime

def generate_slug(title, facility_name):
    """Generate URL-friendly slug from title"""
    # Combine facility name and title for unique slug
    text = f"{facility_name} {title}".lower()
    # Remove special characters and replace spaces with hyphens
    slug = re.sub(r'[^a-z0-9\s-]', '', text)
    slug = re.sub(r'\s+', '-', slug)
    slug = re.sub(r'-+', '-', slug)
    slug = slug.strip('-')
    # Limit length
    slug = slug[:80]
    # Add timestamp for uniqueness
    timestamp = datetime.now().strftime('%Y%m%d')
    return f"{slug}-{timestamp}"

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

# Get the articles we just created (they have no slug)
response = articles.query.fetch_objects(
    limit=10
)

print("Checking articles for missing slugs...")
updated = 0

for article in response.objects:
    if not article.properties.get('slug'):
        title = article.properties.get('title', '')
        facility = article.properties.get('facility_name', '')
        
        if title:
            # Generate slug
            slug = generate_slug(title, facility)
            
            # Update article with slug
            articles.data.update(
                uuid=article.uuid,
                properties={
                    'slug': slug
                }
            )
            
            print(f"✅ Updated article {article.uuid}")
            print(f"   Title: {title[:50]}...")
            print(f"   Slug: {slug}")
            print(f"   URL: https://cleankitchens.org/{slug}")
            print()
            updated += 1

print(f"\nUpdated {updated} articles with slugs")
client.close()