import sqlite3
import os
import sys
from pathlib import Path

SCRIPTS_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(SCRIPTS_DIR)
DB_DIR = Path(ROOT_DIR) / "database"


def get_databases():
    if not DB_DIR.exists():
        print(f"Database folder not found: {DB_DIR}")
        sys.exit(1)
    dbs = sorted(DB_DIR.glob("*.sqlite"))
    if not dbs:
        print("No .sqlite files found in database/")
        sys.exit(1)
    return dbs


def check_db(db_path):
    conn = sqlite3.connect(str(db_path), timeout=30)
    conn.row_factory = sqlite3.Row

    total = conn.execute("SELECT COUNT(*) FROM posts").fetchone()[0]
    if total == 0:
        conn.close()
        return None

    images = conn.execute(
        "SELECT COUNT(*) FROM posts WHERE images IS NOT NULL AND images != '' AND images != '[]'"
    ).fetchone()[0]
    snippet = conn.execute(
        "SELECT COUNT(*) FROM posts WHERE snippet IS NOT NULL AND snippet != ''"
    ).fetchone()[0]
    ai_title = conn.execute(
        "SELECT COUNT(*) FROM posts WHERE ai_title IS NOT NULL AND ai_title != ''"
    ).fetchone()[0]
    ai_article = conn.execute(
        "SELECT COUNT(*) FROM posts WHERE ai_content IS NOT NULL AND ai_content != ''"
    ).fetchone()[0]

    conn.close()
    return {
        "total": total,
        "images": images,
        "snippet": snippet,
        "ai_title": ai_title,
        "ai_article": ai_article,
    }


def pct(filled, total):
    return (filled / total * 100) if total > 0 else 0


def bar(filled, total, width=20):
    filled_blocks = int(width * filled / total) if total > 0 else 0
    return "#" * filled_blocks + "-" * (width - filled_blocks)


def main():
    dbs = get_databases()

    grand_total = 0
    grand_images = 0
    grand_snippet = 0
    grand_ai_title = 0
    grand_ai_article = 0

    print("=" * 60)
    print("  DATABASE SUMMARY")
    print("=" * 60)

    for db_path in dbs:
        stats = check_db(db_path)
        if stats is None:
            continue

        name = db_path.stem
        t = stats["total"]
        img = stats["images"]
        snip = stats["snippet"]
        title = stats["ai_title"]
        article = stats["ai_article"]

        grand_total += t
        grand_images += img
        grand_snippet += snip
        grand_ai_title += title
        grand_ai_article += article

        print(f"\n  {name} ({t} posts)")
        print(f"    Images     : {bar(img, t)} {img}/{t} ({pct(img, t):.1f}%)")
        print(f"    Snippet    : {bar(snip, t)} {snip}/{t} ({pct(snip, t):.1f}%)")
        print(f"    AI Title   : {bar(title, t)} {title}/{t} ({pct(title, t):.1f}%)")
        print(f"    AI Article : {bar(article, t)} {article}/{t} ({pct(article, t):.1f}%)")

    if grand_total > 0:
        print("\n" + "=" * 60)
        print(f"  TOTAL ({grand_total} posts)")
        print(f"    Images     : {bar(grand_images, grand_total)} {grand_images}/{grand_total} ({pct(grand_images, grand_total):.1f}%)")
        print(f"    Snippet    : {bar(grand_snippet, grand_total)} {grand_snippet}/{grand_total} ({pct(grand_snippet, grand_total):.1f}%)")
        print(f"    AI Title   : {bar(grand_ai_title, grand_total)} {grand_ai_title}/{grand_total} ({pct(grand_ai_title, grand_total):.1f}%)")
        print(f"    AI Article : {bar(grand_ai_article, grand_total)} {grand_ai_article}/{grand_total} ({pct(grand_ai_article, grand_total):.1f}%)")
        print("=" * 60)


if __name__ == "__main__":
    main()
