"""Refresh Google Calendar events. Optional: run from cron to keep the widget fresh.

    */10 * * * * /home/USER/virtualenv/planner/3.11/bin/python /home/USER/planner/sync.py >/dev/null 2>&1

The app also refreshes by itself whenever the page or widget loads and the
copy is more than 10 minutes old, so cron is only a nice-to-have.
"""
import os
import sys
from datetime import datetime
from zoneinfo import ZoneInfo

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import config  # noqa: E402
import db      # noqa: E402
import gcal    # noqa: E402


def main() -> int:
    db.init_db()
    conn = db.connect()
    try:
        err = gcal.sync_if_stale(conn, datetime.now(ZoneInfo(config.TIMEZONE)).date(), force=True)
    finally:
        conn.close()
    if err:
        print(f"sync failed: {err}", file=sys.stderr)
        return 1
    print("sync ok")
    return 0


if __name__ == "__main__":
    sys.exit(main())
