import sys
import os

SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(SCRIPTS_DIR)

if ROOT_DIR not in sys.path:
    sys.path.insert(0, ROOT_DIR)

from pinscrape.database import get_all_db_files, get_db_connection, update_all_status


def print_progress(current, total, prefix="", bar_length=40):
    if total == 0:
        return
    pct = current / total
    filled = int(bar_length * pct)
    bar = "█" * filled + "░" * (bar_length - filled)
    sys.stdout.write(f"\r  {prefix} [{bar}] {current}/{total} ({pct*100:.0f}%)")
    sys.stdout.flush()
    if current == total:
        sys.stdout.write("\n")


def delete_ai_title():
    db_files = get_all_db_files()
    if not db_files:
        print("No database files found.")
        return

    total = len(db_files)
    print(f"\n  Found {total} database file(s)\n")
    total_cleared = 0

    for i, db_path in enumerate(db_files, 1):
        conn = get_db_connection(str(db_path))
        cursor = conn.execute("UPDATE posts SET ai_title = NULL, updated_at = datetime('now') WHERE ai_title IS NOT NULL AND ai_title != ''")
        affected = cursor.rowcount
        conn.commit()
        conn.close()

        result = update_all_status(str(db_path))
        total_cleared += affected
        print(f"  [{i}/{total}] {db_path.name}: cleared {affected} ai_title row(s) -> status 0:{result['status_0']} 1:{result['status_1']} 2:{result['status_2']}")
        print_progress(i, total, prefix="Overall")

    print(f"\n  Done. Total cleared: {total_cleared} ai_title row(s) across {total} database(s)")


if __name__ == "__main__":
    delete_ai_title()
    print("Done.")
