import os
import re
import shutil

def create_logdvi(isbn, book):
    """
    Create a log file from the DVI file using dvips.
    """
    create_logdvi = f'dvips -o {isbn}_{book}.ps {isbn}_{book}.dvi 2> logdvi.txt'
    os.system(create_logdvi)
    print(f"Created logdvi.txt for {isbn}_{book}.dvi")

def parse_logdvi(log_file):
    """
    Parse the log file to find the pages where each image appears.
    Returns a dictionary with image names as keys and page numbers as values.
    """
    image_pages = {}
    if not os.path.exists(log_file):
        print(f"Error: {log_file} does not exist.")
        return image_pages

    with open(log_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # Regex to find image inclusion commands in the log file
    page_pattern = re.compile(r'\[(\d+)')
    image_pattern = re.compile(r'<.*?/(.*?\.eps)>')

    pages = page_pattern.finditer(content)
    for page_match in pages:
        page_number = int(page_match.group(1))
        start = page_match.end()
        end = content.find(']', start)
        if end == -1:
            continue
        page_content = content[start:end]
        images = image_pattern.findall(page_content)
        for image_name in images:
            image_name = os.path.basename(image_name)  # Extract only the file name
            if image_name not in image_pages:
                image_pages[image_name] = page_number
                print(f"Found image: {image_name} on page: {page_number}")

    return image_pages

def rename_images(image_pages, images_dir):
    """
    Rename the images in the images directory based on the page numbers.
    Returns a dictionary with old image names as keys and new image names as values.
    """
    renamed_images = {}
    for image_name, page_number in image_pages.items():
        if image_name == "ILpubEce.eps" or re.match(r'Picto.*\.eps', image_name):
            print(f"Skipping {image_name} as it is excluded from renaming.")
            continue

        old_path = os.path.join(images_dir, image_name)
        tmp_name = os.path.basename(image_name)[4:]
        new_name = f"{page_number:03d}_{tmp_name}"
        new_path = os.path.join(images_dir, new_name)

        if os.path.exists(old_path):
            shutil.move(old_path, new_path)
            print(f"Renamed {old_path} to {new_path}")
            renamed_images[image_name] = new_name
        else:
            print(f"Warning: {old_path} does not exist and was not renamed.")

    return renamed_images

def update_latex_files(renamed_images, src_dir):
    """
    Update the LaTeX source files with the new image names.
    """
    for root, _, files in os.walk(src_dir):
        for file in files:
            if file.endswith('.tex'):
                file_path = os.path.join(root, file)
                with open(file_path, 'r', encoding='utf-8') as f:
                    content = f.read()

                for old_name, new_name in renamed_images.items():
                    old_base_name = os.path.splitext(old_name)[0]
                    new_base_name = os.path.splitext(new_name)[0]
                    content = content.replace(old_base_name, new_base_name)

                with open(file_path, 'w', encoding='utf-8') as f:
                    f.write(content)
                print(f"Updated {file_path}")

def main():
    # Directories
    current_dir = os.path.dirname(os.path.abspath(__file__))
    isbn = os.path.basename(current_dir).split('_')[0]
    book = "ILTNSI"  # Replace with the actual book name if different
    images_dir = os.path.join(os.path.dirname(current_dir), f"{isbn}_IMAGES")
    src_dir = os.path.join(current_dir, 'src')
    log_file = os.path.join(current_dir, 'logdvi.txt')

    print(f"Current directory: {current_dir}")
    print(f"ISBN: {isbn}")
    print(f"Book: {book}")
    print(f"Images directory: {images_dir}")
    print(f"Source directory: {src_dir}")
    print(f"Log file: {log_file}")

    # Create log file from DVI
    create_logdvi(isbn, book)

    # Parse log file to find image pages
    image_pages = parse_logdvi(log_file)
    if not image_pages:
        print("No images found in the log file.")
        return

    # Rename images
    renamed_images = rename_images(image_pages, images_dir)
    if not renamed_images:
        print("No images were renamed.")
        return

    # Update LaTeX source files
    update_latex_files(renamed_images, src_dir)

if __name__ == "__main__":
    main()
