#!/usr/bin/env python3

# DeleteFolderHashes.py
# Deletes "folder" hashes.

# For use after splitting folder hashes to individual hash files.
# 100% AI Generated code.

import sys
import ctypes
import stat
from pathlib import Path

FILE_ATTRIBUTE_NORMAL = 0x80


def make_writable(filepath: Path) -> None:

    """Ensures file attributes allow deletion on Windows/NTFS."""
    if sys.platform == "win32":
        ctypes.windll.kernel32.SetFileAttributesW(str(filepath), FILE_ATTRIBUTE_NORMAL)
    else:
        filepath.chmod(stat.S_IWRITE)


def delete_folder_hash_files(root_path: str) -> None:

    target_dir = Path(root_path).resolve()
    if not target_dir.is_dir():
        print(f"Error: Directory '{root_path}' does not exist.")
        sys.exit(1)

    deleted_count = 0

    for hash_file in target_dir.rglob("*.hash"):
        if hash_file.is_file():
            # Compare hash file stem against parent directory name (case-insensitive)
            if hash_file.stem.casefold() == hash_file.parent.name.casefold():
                try:
                    make_writable(hash_file)
                    hash_file.unlink()
                    print(f"Deleted: {hash_file}")
                    deleted_count += 1
                except Exception as e:
                    print(f"Failed to delete '{hash_file}': {e}")

    print(f"\nCompleted. Deleted {deleted_count} folder hash file(s).")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python DeleteFolderHashes.py <root_directory_path>")
        sys.exit(1)

    delete_folder_hash_files(sys.argv[1])
