"""
Fix blog post published_at dates to be in the past
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent))

from sqlalchemy.orm import Session
from src.shared.config.database import SessionLocal
from src.models.blog import BlogPost
from datetime import datetime, timedelta

def fix_blog_dates():
    """Update all blog posts to have published_at dates in the past"""
    db: Session = SessionLocal()
    
    try:
        # Get all published posts
        posts = db.query(BlogPost).filter(BlogPost.is_published == True).order_by(BlogPost.created_at.asc()).all()
        
        if not posts:
            print("No published posts found.")
            return
        
        # Set base date to 60 days ago
        base_date = datetime.utcnow() - timedelta(days=60)
        
        updated = 0
        for i, post in enumerate(posts):
            # Set each post's date going backwards from base_date
            # Each post is 2 days earlier than the previous one
            new_date = base_date - timedelta(days=i * 2)
            post.published_at = new_date
            updated += 1
        
        db.commit()
        print(f"Successfully updated {updated} blog posts with past published_at dates")
        
    except Exception as e:
        db.rollback()
        print(f"Error fixing blog dates: {str(e)}")
        raise
    finally:
        db.close()

if __name__ == "__main__":
    print("Fixing blog post published_at dates...")
    fix_blog_dates()
    print("Done!")

