"""
Professional time parsing module for Chinese and English time expressions.

This module provides a robust parser for natural language time expressions,
supporting both Chinese and English formats with proper whitespace handling.
"""

import datetime
from typing import Optional

from .expression import TimeExpression
from .err import TokenUnhandledException, MultipleSpecificationException


def parse(text: str, now: Optional[datetime.datetime] = None) -> datetime.datetime:
    """
    Parse a time expression and return a datetime object.
    
    Args:
        text: The time expression to parse
        now: The reference time (defaults to current time)
        
    Returns:
        A datetime object representing the parsed time
        
    Raises:
        TokenUnhandledException: If the input cannot be parsed
    """
    return TimeExpression.parse(text, now)


class Parser:
    """
    Parser for time expressions with backward compatibility.
    
    Maintains the original interface:
    >>> parser = Parser()
    >>> result = parser.parse("10分钟后")
    """
    
    def __init__(self, now: Optional[datetime.datetime] = None):
        self.now = now or datetime.datetime.now()
    
    def parse(self, text: str) -> datetime.datetime:
        """
        Parse a time expression and return a datetime object.
        This maintains backward compatibility with the original interface.
        
        Args:
            text: The time expression to parse
            
        Returns:
            A datetime object representing the parsed time
            
        Raises:
            TokenUnhandledException: If the input cannot be parsed
        """
        return TimeExpression.parse(text, self.now)
    
    def digest_chinese_number(self, text: str) -> tuple[str, int]:
        """
        Parse a Chinese number from the beginning of text and return the rest and the parsed number.
        
        This matches the interface of the original digest_chinese_number method.
        
        Args:
            text: Text that may start with a Chinese number
            
        Returns:
            Tuple of (remaining_text, parsed_number)
        """
        from .chinese_number import ChineseNumberParser
        parser = ChineseNumberParser()
        return parser.digest(text)