from datetime import datetime, timedelta, time, timezone
from db import one

# V1 operates in India. Fixed UTC+05:30 avoids a tzdata installation on Windows.
IST = timezone(timedelta(hours=5, minutes=30), 'Asia/Kolkata')

def next_delivery(db, route_id, clock=None):
    route = one(db, 'SELECT * FROM routes WHERE id=? AND business_id=1', (route_id,))
    if not route or not route['active']:
        raise ValueError('Route is unavailable; staff must assign an active route.')
    clock = clock or datetime.now(IST)
    if clock.tzinfo is None:
        raise ValueError('Scheduling requires a timezone-aware clock')
    clock = clock.astimezone(IST)
    date = clock.date() + timedelta(days=(route['weekday'] - clock.weekday()) % 7)
    for _ in range(53):
        cutoff = datetime.combine(date - timedelta(days=route['cutoff_days']), time.fromisoformat(route['cutoff_time']), IST)
        departure = datetime.combine(date, time.fromisoformat(route['departure_time']), IST)
        run = one(db, 'SELECT * FROM delivery_schedules WHERE route_id=? AND date=?', (route_id,date.isoformat()))
        holiday = one(db, 'SELECT id FROM holidays WHERE business_id=1 AND date=?', (date.isoformat(),))
        if clock < cutoff and clock < departure and not holiday and not (run and run['departed']):
            return date.isoformat()
        date += timedelta(days=7)
    raise ValueError('No available delivery date within a year')
