"""Template parsing utilities for filename pattern extraction.

This module provides utilities for extracting template patterns from filenames
by replacing digit sequences with placeholders. This enables grouping files
that follow the same naming pattern (e.g., IMG_0001.jpg, IMG_0002.jpg).

The template extraction happens early in the pipeline (during SHA binning) and
is cached on PhotoFile objects for use in later stages.
"""

from __future__ import annotations

import re

# Type alias for digit sequence indices extracted from filenames
# Example: "IMG_1234_5678.jpg" → ("1234", "5678")
INDEX_T = tuple[str, ...]


def extract_template(text: str) -> tuple[str, INDEX_T]:
    """Extract template and digit groups from text.

    Replaces all digit sequences with placeholders {P0}, {P1}, etc.
    This enables grouping files with similar naming patterns.

    The function scans the input text for consecutive digit sequences and
    replaces each with a placeholder of the form {P0}, {P1}, etc. The
    original digit sequences are returned as a tuple for later reconstruction.

    Args:
        text: Text to parse (typically filename stem without extension)

    Returns:
        Tuple of (template_string, digit_sequences) where:
        - template_string: Text with digit sequences replaced by {P0}, {P1}, etc.
        - digit_sequences: Tuple of original digit strings in order of appearance

    Examples:
        >>> template, digits = extract_template("IMG_1234")
        >>> print(template)
        IMG_{P0}
        >>> print(digits)
        ('1234',)

        >>> template, digits = extract_template("2023_05_IMG_1234_5678")
        >>> print(template)
        {P0}_{P1}_IMG_{P2}_{P3}
        >>> print(digits)
        ('2023', '05', '1234', '5678')

        >>> template, digits = extract_template("no_digits_here")
        >>> print(template)
        no_digits_here
        >>> print(digits)
        ()

        >>> template, digits = extract_template("12345")
        >>> print(template)
        {P0}
        >>> print(digits)
        ('12345',)
    """
    digits: list[str] = []

    def repl(m: re.Match[str]) -> str:
        """Replace matched digit sequence with placeholder {PN} and capture digits."""
        digits.append(m.group(0))
        return f"{{P{len(digits) - 1}}}"

    template: str = re.sub(r"\d+", repl, text)
    return template, tuple(digits)
