"""
DateTime utilities for microservices
"""

from datetime import datetime, timezone, timedelta
from typing import Optional
import pytz

def utc_now() -> datetime:
    """Get current UTC datetime"""
    return datetime.now(timezone.utc)

def madrid_now() -> datetime:
    """Get current Madrid datetime"""
    madrid_tz = pytz.timezone('Europe/Madrid')
    return datetime.now(madrid_tz)

def to_utc(dt: datetime) -> datetime:
    """Convert datetime to UTC"""
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt.astimezone(timezone.utc)

def to_madrid(dt: datetime) -> datetime:
    """Convert datetime to Madrid timezone"""
    madrid_tz = pytz.timezone('Europe/Madrid')
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt.astimezone(madrid_tz)

def format_datetime(dt: datetime, format_str: str = "%Y-%m-%d %H:%M:%S") -> str:
    """Format datetime as string"""
    return dt.strftime(format_str)

def parse_datetime(dt_str: str, format_str: str = "%Y-%m-%d %H:%M:%S") -> datetime:
    """Parse datetime from string"""
    return datetime.strptime(dt_str, format_str)

def is_business_hours(dt: Optional[datetime] = None) -> bool:
    """Check if datetime is during business hours (9 AM - 6 PM Madrid time)"""
    if dt is None:
        dt = madrid_now()
    
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    
    madrid_dt = to_madrid(dt)
    
    # Check if it's a weekday (Monday=0, Sunday=6)
    if madrid_dt.weekday() >= 5:  # Weekend
        return False
    
    # Check if it's business hours
    return 9 <= madrid_dt.hour < 18

def next_business_day(dt: Optional[datetime] = None) -> datetime:
    """Get next business day"""
    if dt is None:
        dt = madrid_now()
    
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    
    madrid_dt = to_madrid(dt)
    
    # Add days until we reach a weekday
    while madrid_dt.weekday() >= 5:  # Weekend
        madrid_dt += timedelta(days=1)
    
    # Set to 9 AM
    return madrid_dt.replace(hour=9, minute=0, second=0, microsecond=0)