import os
import re
import pdfplumber

# Define the directory containing the PDF files
pdf_directory = '/var/www/erp.myalextech.co.ke/public_html/MUCO'

# Function to extract the KCSE index number from the first page of the PDF
def extract_kcse_index(pdf_path):
    try:
        with pdfplumber.open(pdf_path) as pdf:
            first_page = pdf.pages[0]
            text = first_page.extract_text()

            # Define a pattern for the KCSE index number (modify this regex as needed)
            pattern = re.compile(r'KCSE Index:\s*(\d+)', re.IGNORECASE)
            
            # Search for the pattern in the text
            match = pattern.search(text)
            if match:
                kcse_index = match.group(1).strip()
                return kcse_index
            
    except Exception as e:
        print(f"Error reading {pdf_path}: {e}")
    
    return None

# Function to sanitize filenames
def sanitize_filename(filename):
    # Remove any invalid characters and trim whitespace
    filename = re.sub(r'[<>:"/\\|?*\n]', '_', filename)
    return filename.strip()

# Function to truncate filenames to a maximum length
def truncate_filename(filename, max_length=255):
    if len(filename) > max_length:
        filename = filename[:max_length]
        filename = re.sub(r'[<>:"/\\|?*\n]', '_', filename)
    return filename

# Iterate over all PDF files in the directory
for filename in os.listdir(pdf_directory):
    if filename.endswith('.pdf'):
        full_path = os.path.join(pdf_directory, filename)
        kcse_index = extract_kcse_index(full_path)
        
        if kcse_index:
            new_filename = f"{sanitize_filename(kcse_index)}.pdf"
            new_filename = truncate_filename(new_filename)  # Truncate if necessary
            new_full_path = os.path.join(pdf_directory, new_filename)
            
            # Ensure we do not overwrite files unintentionally
            if not os.path.exists(new_full_path):
                try:
                    os.rename(full_path, new_full_path)
                    print(f'Renamed: {filename} -> {new_filename}')
                except Exception as e:
                    print(f"Error renaming {filename}: {e}")
            else:
                print(f'Skipped: {filename} (File already exists)')
        else:
            print(f'Skipped: {filename} (KCSE Index not found)')

print("Batch renaming completed.")
