#!/usr/bin/env python3
from pathlib import Path
import subprocess

BASE = Path("/home/dayhanbiz/public_html/biblioteka/тестирование скриптов/Сортировка по шрифту")
SOURCE = BASE / "Неотсортированные файлы"
TARGET = BASE / "Отсортированные - Фарси"
LOG_DIR = BASE / "Скрипты" / "Temporary process files"

TARGET.mkdir(parents=True, exist_ok=True)
LOG_DIR.mkdir(parents=True, exist_ok=True)

# Только уникальные буквы фарси
FARSI_CHARS = set(['پ','چ','ژ','گ'])

def extract_pages_5_7_9_18(pdf_path):
    try:
        temp_prefix = LOG_DIR / pdf_path.stem
        
        # Конвертируем страницы 5,7,9,18 в изображения
        subprocess.run([
            'pdftoppm', '-png', '-r', '300', '-f', '5', '-l', '18',
            str(pdf_path), str(temp_prefix)
        ], check=True, timeout=120)

        page_files = sorted(LOG_DIR.glob(f"{pdf_path.stem}*.png"))
        if not page_files:
            return "", None

        text_total = ""
        for page_file in page_files:
            page_num = int(page_file.stem.split('-')[-1])
            if page_num not in [5, 7, 9, 18]:
                if page_file.exists():
                    page_file.unlink()
                continue

            result = subprocess.run([
                'tesseract', str(page_file), 'stdout', '-l', 'fas+ara', '--psm', '6'
            ], stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=80)

            if result.returncode == 0:
                text_total += result.stdout.decode('utf-8', errors='ignore') + "\n"

            if page_file.exists():
                page_file.unlink()

        log_file = LOG_DIR / f"{pdf_path.stem}_pages5-7-9-18.txt"
        with open(log_file, "w", encoding="utf-8") as f:
            f.write(text_total)

        return text_total, log_file

    except Exception as e:
        print(f"Ошибка: {pdf_path.name} → {e}")
        return "", None

print("=== Скрипт 3. Проверка страниц 5,7,9,18 на фарси (Tesseract) ===")
pdf_files = list(SOURCE.glob("*.pdf"))
print(f"Найдено файлов: {len(pdf_files)}\n")

moved = 0
for pdf in pdf_files:
    text, log_file = extract_pages_5_7_9_18(pdf)
    farsi_count = sum(1 for c in text if c in FARSI_CHARS)
    
    if farsi_count >= 25:
        try:
            pdf.rename(TARGET / pdf.name)
            print(f"→ Фарси ({farsi_count} уникальных букв): {pdf.name}")
            moved += 1
            print(f"   Лог сохранён: {log_file.name}")
        except Exception as e:
            print(f"Ошибка перемещения {pdf.name}: {e}")
    else:
        print(f"   Не фарси ({farsi_count} букв): {pdf.name}")
        if log_file and log_file.exists():
            log_file.unlink()

print(f"\n=== Завершено. Перемещено в Фарси: {moved} файлов ===")
print(f"Логи сохранены только для перемещённых файлов.")
