"""Shared output filename template rendering utilities."""

from __future__ import annotations

import re
from datetime import datetime
from pathlib import Path

_SEQ_PATTERN = re.compile(r"\{seq(?::(\d+))?\}")


def render_output_path_template(
    template: str,
    *,
    profile_name: str,
    now: datetime | None = None,
) -> Path:
    current = now or datetime.now()
    values = {
        "profile": profile_name,
        "yyyy": current.strftime("%Y"),
        "MM": current.strftime("%m"),
        "dd": current.strftime("%d"),
        "HH": current.strftime("%H"),
        "mm": current.strftime("%M"),
        "ss": current.strftime("%S"),
        "date": current.strftime("%Y%m%d"),
        "time": current.strftime("%H%M%S"),
    }
    seq_widths: list[int] = []

    def _seq_replacer(match: re.Match[str]) -> str:
        width = int(match.group(1) or "1")
        token_idx = len(seq_widths)
        seq_widths.append(width)
        return f"__WORAI_SEQ_{token_idx}__"

    protected = _SEQ_PATTERN.sub(_seq_replacer, template)
    base = protected.format(**values)
    if not seq_widths:
        return Path(base)

    seq = 1
    while True:
        rendered = base
        for idx, width in enumerate(seq_widths):
            rendered = rendered.replace(
                f"__WORAI_SEQ_{idx}__",
                str(seq).zfill(width),
            )
        candidate = Path(rendered)
        if not candidate.exists():
            return candidate
        seq += 1
