import requests
import sqlite3
import os
import logging
from config import WP_URL, WP_USERNAME, WP_APP_PASSWORD

logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")

def delete_all_wp_posts():
    auth = (WP_USERNAME, WP_APP_PASSWORD)
    posts_url = f"{WP_URL.rstrip('/')}/wp-json/wp/v2/posts"
    
    logging.info("Fetching all posts from WordPress...")
    
    # We fetch posts (default per_page=100)
    # We need to loop since there could be multiple pages
    deleted_count = 0
    while True:
        try:
            response = requests.get(posts_url, params={"per_page": 100, "status": "any"}, auth=auth, timeout=20)
            if response.status_code != 200:
                logging.error(f"Failed to fetch posts: {response.text}")
                break
                
            posts = response.json()
            if not posts:
                logging.info("No posts found to delete.")
                break
                
            logging.info(f"Found {len(posts)} posts in this batch. Deleting...")
            for post in posts:
                post_id = post["id"]
                title = post["title"]["rendered"]
                # force=true completely deletes it (doesn't just move it to trash)
                del_resp = requests.delete(f"{posts_url}/{post_id}", params={"force": "true"}, auth=auth, timeout=20)
                if del_resp.status_code == 200:
                    logging.info(f"Successfully deleted post ID {post_id}: '{title}'")
                    deleted_count += 1
                else:
                    logging.error(f"Failed to delete post ID {post_id}: {del_resp.text}")
            
            # If we deleted less than 100, we probably reached the end, but let's loop to be sure
            if len(posts) < 100:
                break
        except Exception as e:
            logging.error(f"Error occurred during post deletion: {e}")
            break
            
    logging.info(f"Total deleted posts: {deleted_count}")

def reset_local_db():
    db_path = os.path.join(os.path.dirname(__file__), "processed_posts.db")
    if os.path.exists(db_path):
        try:
            os.remove(db_path)
            logging.info("Local SQLite database deleted and reset.")
        except Exception as e:
            logging.info(f"Error resetting database: {e}")
            # Fallback to truncating table
            try:
                conn = sqlite3.connect(db_path)
                cursor = conn.cursor()
                cursor.execute("DROP TABLE IF EXISTS processed_posts")
                conn.commit()
                conn.close()
                logging.info("Local SQLite database table dropped.")
            except Exception as dbe:
                logging.error(f"Failed to drop table: {dbe}")
    else:
        logging.info("No local SQLite database found to reset.")

if __name__ == "__main__":
    print("=== STARTING CLEANUP AND RESET ===")
    delete_all_wp_posts()
    reset_local_db()
    print("=== CLEANUP AND RESET COMPLETE ===")
