#!/usr/bin/env python3
from __future__ import annotations

import requests

from _common import API_ROOT, api_request, build_auth_parser, dump, normalize_feishu_event_time, tenant_access_token


def main() -> int:
    parser = build_auth_parser("Update Feishu calendar event")
    parser.add_argument("--calendar-id", required=True)
    parser.add_argument("--event-id", required=True)
    parser.add_argument("--summary", default="")
    parser.add_argument("--start", default="", help="RFC3339 timestamp with timezone offset or unix timestamp seconds")
    parser.add_argument("--end", default="", help="RFC3339 timestamp with timezone offset or unix timestamp seconds")
    parser.add_argument("--timezone", default="Asia/Shanghai")
    parser.add_argument("--description", default="")
    args = parser.parse_args()
    token = tenant_access_token(args.app_id, args.app_secret)
    payload = {}
    for key, value in {
        "summary": args.summary,
        "description": args.description,
    }.items():
        if value:
            payload[key] = value
    if args.start:
        payload["start_time"] = normalize_feishu_event_time(args.start, args.timezone)
    if args.end:
        payload["end_time"] = normalize_feishu_event_time(args.end, args.timezone)
    if not payload:
        raise SystemExit("at least one of --summary/--start/--end/--description is required")
    result = api_request(
        "PATCH",
        f"{API_ROOT}/calendar/v4/calendars/{args.calendar_id}/events/{args.event_id}",
        token=token,
        json=payload,
    )
    dump(result)
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
