#!/usr/bin/env python3

# Split Hash files Recursively.
# Scans a directory tree for .hash files whose stem name matches the parent folder.
# 100% AI Generated code. And not bad.

import sys
import re
import shutil
import ctypes
from pathlib import Path
from contextlib import contextmanager

FILE_ATTRIBUTE_NORMAL = 0x80

# Matches metadata line format: #algo#filename#timestamp
META_PATTERN = re.compile(r"^#([a-zA-Z0-9_-]+)#(.+)#([^#]+)$")


@contextmanager
def writable_file(filepath: Path):

    path_str = str(filepath)
    orig = -1
    if filepath.exists():
        orig = ctypes.windll.kernel32.GetFileAttributesW(path_str)
        if orig != -1:
            ctypes.windll.kernel32.SetFileAttributesW(path_str, FILE_ATTRIBUTE_NORMAL)
    try:
        yield
    finally:
        if orig != -1 and filepath.exists():
            ctypes.windll.kernel32.SetFileAttributesW(path_str, orig)


def copy_file_attributes(src: Path, dst: Path) -> None:

    """Copies timestamps, stat bits, and exact Windows file attributes (Hidden, ReadOnly, etc.)."""
    
    shutil.copystat(src, dst)
    if sys.platform == "win32":
        attrs = ctypes.windll.kernel32.GetFileAttributesW(str(src))
        if attrs != -1:
            ctypes.windll.kernel32.SetFileAttributesW(str(dst), attrs)



def get_existing_filenames(hash_path: Path) -> set[str]:
    
    """Reads an existing .hash file and extracts all referenced filenames (case-folded)."""
    
    filenames = set()
    if not hash_path.is_file():
        return filenames

    try:
        with open(hash_path, "r", encoding="utf-8", errors="ignore") as f:
            for line in f:
                line_str = line.strip()
                meta_match = META_PATTERN.match(line_str)
                if meta_match:
                    filenames.add(meta_match.group(2).casefold())
                elif " " in line_str or "\t" in line_str:
                    # Parse standard checksum hash lines: "hash *filename" or "hash filename"
                    parts = line_str.split(maxsplit=1)
                    if len(parts) == 2:
                        fname = parts[1].lstrip("*").strip()
                        filenames.add(fname.casefold())
    except Exception:
        pass

    return filenames



def split_hash_file(source_path: Path) -> tuple[int, int]:
    
    """Splits a single folder hash file into individual .hash files, respecting original linebreaks."""
    
    output_dir = source_path.parent

    try:
        with open(source_path, "r", encoding="utf-8", errors="ignore", newline="") as f:
            lines = f.readlines()

            # Detect original line ending format (\r\n vs \n)
            if isinstance(f.newlines, tuple):
                source_newline = f.newlines[0]
            elif isinstance(f.newlines, str):
                source_newline = f.newlines
            else:
                source_newline = "\n"
    except Exception as e:
        print(f"Error reading '{source_path}': {e}")
        return 0, 0

    header_lines = []
    body_lines = []
    found_first_meta = False

    for line in lines:
        if not found_first_meta:
            if META_PATTERN.match(line.strip()):
                found_first_meta = True
                body_lines.append(line)
            else:
                header_lines.append(line)
        else:
            body_lines.append(line)

    # Raw header lines retain their exact original line endings
    dynamic_header = "".join(header_lines)

    current_meta_line = None
    current_filename = None
    count = 0
    skipped = 0

    target_contents_cache: dict[Path, set[str]] = {}

    for line in body_lines:
        line_str = line.strip()
        if not line_str:
            continue

        meta_match = META_PATTERN.match(line_str)
        if meta_match:
            current_meta_line = line_str
            current_filename = meta_match.group(2)
            continue

        if current_meta_line and current_filename and (" " in line_str or "\t" in line_str):
            hash_line = line_str
            stem = Path(current_filename).stem
            out_filepath = output_dir / f"{stem}.hash"

            if out_filepath not in target_contents_cache:
                target_contents_cache[out_filepath] = get_existing_filenames(out_filepath)

            existing_files = target_contents_cache[out_filepath]

            if current_filename.casefold() in existing_files:
                current_meta_line = None
                current_filename = None
                skipped += 1
                continue

            if out_filepath.exists():
                mode = "a"
                content = f"{current_meta_line}{source_newline}{hash_line}{source_newline}"

                try:
                    with open(out_filepath, "rb") as check_f:
                        check_f.seek(0, 2)
                        if check_f.tell() > 0:
                            check_f.seek(-1, 2)
                            if check_f.read(1) not in (b"\n", b"\r"):
                                content = f"{source_newline}{content}"
                except Exception:
                    pass
            else:
                mode = "w"
                content = (
                    f"{dynamic_header}"
                    f"{current_meta_line}{source_newline}"
                    f"{hash_line}{source_newline}"
                )

            with writable_file(out_filepath):
                # Pass newline="" to prevent Windows implicit LF -> CRLF translation
                with open(out_filepath, mode, encoding="utf-8", newline="") as out_f:
                    out_f.write(content)

            copy_file_attributes(source_path, out_filepath)

            existing_files.add(current_filename.casefold())
            count += 1

            current_meta_line = None
            current_filename = None

    return count, skipped




def process_tree(root_path: str, log_filename: str = "SplitHashesRecursive_PROCESSED.log") -> None:
    
    """Main entry point for hash splitting routines."""

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

    log_path = target_dir / log_filename
    processed_paths = []
    matched_files = 0
    total_hashes_created = 0
    total_hashes_skipped = 0

    # Recursively traverse directory tree looking for matching folder hash files
    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():
                full_path = str(hash_file.resolve())
                print(f"\nFound folder hash: {full_path}")

                created, skipped = split_hash_file(hash_file)
                matched_files += 1
                total_hashes_created += created
                total_hashes_skipped += skipped

                log_entry = f"{full_path} ==> {skipped} individual hash file(s) skipped." if skipped > 0 else f"{full_path} ==> OK!"
                processed_paths.append(log_entry)

                print(f"\n  -> Created {created} individual hash file(s)")
                if skipped > 0:
                    print(f"  -> Skipped {skipped} individual hash file(s)\n")

    # Save log file with full paths and per-file skip status
    if processed_paths:
        with open(log_path, "w", encoding="utf-8") as log_file:
            log_file.write("\n".join(processed_paths) + "\n")
        print(f"Log written to: {log_path}")
    else:
        print("No matching folder hash files were found.")

    print("\nCompleted tree processing.")
    print(f"Processed {matched_files} folder hash file(s); generated {total_hashes_created} individual hash file(s).")

    if total_hashes_skipped > 0:
        sys.exit(2)


if __name__ == "__main__":

    if len(sys.argv) < 2:
        print("Usage: python SplitHashesRecursive.py <root_directory_path>")
        sys.exit(1)

    process_tree(sys.argv[1])
