#!/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)

# Уникальные арабские буквы (реально отличающиеся от фарси)
ARABIC_UNIQUE = set([
    'أ', 'إ', 'آ', 'ة', 'ء', 'ؤ', 'ئ', 'ى'
])

# Уникальные фарси (для приоритета)
FARSI_UNIQUE = set([
    'پ', 'چ', 'ژ', 'گ'
])

def extract_page_7(pdf_path):
    try:
        temp_prefix = LOG_DIR / pdf_path.stem
        
        subprocess.run([
            'pdftoppm', '-png', '-r', '300', '-f', '7', '-l', '7',
            str(pdf_path), str(temp_prefix)
        ], check=True, timeout=60)

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

        page_file = page_files[0]

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

        text = result.stdout.decode('utf-8', errors='ignore') if result.returncode == 0 else ""

        log_file = LOG_DIR / f"{pdf_path.stem}_page7.txt"
        with open(log_file, "w", encoding="utf-8") as f:
            f.write(text)

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

        return text, log_file

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

print("=== Скрипт 4. Проверка 7-й страницы на уникальные арабские буквы ===")
pdf_files = list(SOURCE.glob("*.pdf"))
print(f"Найдено файлов: {len(pdf_files)}\n")

moved = 0
for pdf in pdf_files:
    text, log_file = extract_page_7(pdf)
    
    arabic_count = sum(1 for c in text if c in ARABIC_UNIQUE)
    farsi_count = sum(1 for c in text if c in FARSI_UNIQUE)

    if farsi_count >= 3:
        print(f"   Фарси (приоритет): {pdf.name} ({farsi_count} фарси букв)")
        if log_file and log_file.exists():
            log_file.unlink()
    elif arabic_count >= 5:
        try:
            pdf.rename(TARGET / pdf.name)
            print(f"→ Арабский ({arabic_count} уникальных букв): {pdf.name}")
            moved += 1
            print(f"   Лог сохранён: {log_file.name}")
        except Exception as e:
            print(f"Ошибка перемещения {pdf.name}: {e}")
    else:
        print(f"   Не арабский ({arabic_count} арабских букв): {pdf.name}")
        if log_file and log_file.exists():
            log_file.unlink()

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