"""
Time window utilities for time series validation.

Provides functions for:
- Getting aligned hour windows
- Replacing time window placeholders in SHACL rules
"""

import datetime
import re


def get_aligned_hour_window() -> tuple[datetime.datetime, datetime.datetime]:
    """
    Get the previous complete hour window aligned to hour boundaries.

    Example: If current time is 07:02, returns (06:00, 07:00)

    Returns:
        Tuple of (start_time, end_time) for the previous complete hour
    """
    now = datetime.datetime.now(tz=datetime.timezone.utc)
    # End of window is the start of the current hour
    end_time = now.replace(minute=0, second=0, microsecond=0)
    # Start of window is 1 hour before
    start_time = end_time - datetime.timedelta(hours=1)
    return start_time, end_time


def replace_time_windows_in_shacl(
    shacl_rules: str,
    start_time: datetime.datetime,
    end_time: datetime.datetime,
) -> str:
    """
    Replace time window placeholders in SHACL rules with actual timestamps.

    Replaces patterns like:
    - "60m-ago" or "90m-ago" -> start_time in milliseconds
    - "now" -> end_time in milliseconds

    This ensures exact, non-overlapping time windows.

    Args:
        shacl_rules: SHACL rules string with time placeholders
        start_time: Start datetime for the window
        end_time: End datetime for the window

    Returns:
        Modified SHACL rules with timestamps replaced
    """
    # Convert to milliseconds for CDF API
    start_ms = int(start_time.timestamp() * 1000)
    end_ms = int(end_time.timestamp() * 1000)

    # Replace common time patterns
    # Pattern: "XXm-ago" or "XXh-ago" or "XXd-ago"
    modified = re.sub(
        r'"(\d+[mhd])-ago"',
        f'"{start_ms}"',
        shacl_rules,
    )
    # Pattern: "now"
    modified = re.sub(
        r'"now"',
        f'"{end_ms}"',
        modified,
    )

    return modified
