"""
Register or renew Gmail watch for support mailbox.

Usage:
  python -m fmatch.saas.scripts.gmail_watch --topic projects/PROJECT/topics/TOPIC
"""

from __future__ import annotations

import argparse
import asyncio
import json
import os
from datetime import datetime, timezone

from fmatch.saas.database import session_context
from fmatch.saas.services.gmail_support import GmailSupportService, ensure_mailbox_integration


async def _run(topic: str, labels: list[str]) -> None:
    async with session_context() as db:
        gmail = await GmailSupportService.from_secret(db)
        response = await gmail.register_watch(topic_name=topic, label_ids=labels)

        mailbox = await ensure_mailbox_integration(db, gmail.support_email)
        history_id = response.get("historyId")
        if history_id:
            mailbox.last_history_id = str(history_id)
            mailbox.updated_at = datetime.now(timezone.utc)
            db.add(mailbox)
            await db.commit()

        print(json.dumps(response, indent=2))


def main() -> None:
    parser = argparse.ArgumentParser(description="Register Gmail watch for support inbox.")
    parser.add_argument(
        "--topic",
        default=os.getenv("GMAIL_WATCH_TOPIC"),
        help="Pub/Sub topic name (projects/PROJECT/topics/TOPIC).",
    )
    parser.add_argument(
        "--label",
        action="append",
        default=None,
        help="Label IDs to include (repeatable). Default: INBOX.",
    )
    args = parser.parse_args()

    if not args.topic:
        raise SystemExit("GMAIL_WATCH_TOPIC not set and --topic not provided.")

    labels = args.label or ["INBOX"]
    asyncio.run(_run(args.topic, labels))


if __name__ == "__main__":
    main()
