import time

from app import (
    get_conn,
    apply_order_timeouts,
    ORDER_STATUS_PENDING_PAYMENT,
    ORDER_STATUS_PAID_PENDING_SHIPMENT,
    ORDER_STATUS_SHIPPED,
)


def choose_sleep_seconds(conn):
    cur = conn.cursor()

    cur.execute("""
        SELECT COUNT(*)
        FROM orders
        WHERE order_status = ?
          AND created_at > DATEADD(MINUTE, -1, SYSDATETIME())
    """, ORDER_STATUS_PENDING_PAYMENT)
    recent_unpaid = cur.fetchone()[0]

    if recent_unpaid > 0:
        return 5

    cur.execute("""
        SELECT COUNT(*)
        FROM orders
        WHERE order_status IN (?, ?, ?)
    """, ORDER_STATUS_PENDING_PAYMENT, ORDER_STATUS_PAID_PENDING_SHIPMENT, ORDER_STATUS_SHIPPED)
    active_orders = cur.fetchone()[0]

    if active_orders == 0:
        return 600

    return 60


def main():
    while True:
        sleep_seconds = 30
        conn = None
        try:
            conn = get_conn()
            cur = conn.cursor()
            apply_order_timeouts(cur)
            conn.commit()
            sleep_seconds = choose_sleep_seconds(conn)
            print(f"timeout sweep completed, next_sleep={sleep_seconds}s", flush=True)
        except Exception as e:
            if conn is not None:
                try:
                    conn.rollback()
                except Exception:
                    pass
            print(f"worker error: {e}", flush=True)
            sleep_seconds = 30
        finally:
            if conn is not None:
                try:
                    conn.close()
                except Exception:
                    pass

        time.sleep(sleep_seconds)


if __name__ == "__main__":
    main()
