import os
import sqlite3
from pathlib import Path

BASE_DIR = Path("/home/dayhanbiz/public_html/Библиотека 3-DAMJA")
TEXTS_DIR = BASE_DIR / "extracted_texts"
DB_PATH = BASE_DIR / "search_databases" / "library_search.db"

def sync_index():
    if not TEXTS_DIR.exists():
        return
        
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    
    # Получаем уже проиндексированные хэши книг
    cursor.execute("SELECT hash_name FROM documents")
    indexed_hashes = {row[0] for row in cursor.fetchall()}
    
    book_dirs = [d for d in TEXTS_DIR.iterdir() if d.is_dir()]
    new_count = 0
    
    for book_dir in book_dirs:
        book_hash = book_dir.name
        if book_hash in indexed_hashes:
            continue
            
        cursor.execute("INSERT OR IGNORE INTO documents (hash_name, title) VALUES (?, ?)", (book_hash, book_hash))
        
        page_files = sorted(book_dir.glob("page_*.txt"))
        for p_file in page_files:
            try:
                page_num_str = p_file.stem.split('_')[1]
                page_num = int(page_num_str)
                
                with open(p_file, "r", encoding="utf-8", errors="ignore") as f:
                    content = f.read()
                    
                if content.strip():
                    cursor.execute(
                        "INSERT INTO pages_fts (book_hash, page_number, content) VALUES (?, ?, ?)",
                        (book_hash, page_num, content)
                    )
            except Exception:
                continue
                
        new_count += 1
        indexed_hashes.add(book_hash)
        
    if new_count > 0:
        conn.commit()
        print(f"[AutoSync] Успешно добавлено новых книг в поисковый индекс: {new_count}")
        
    conn.close()

if __name__ == "__main__":
    sync_index()
