"""OAuth2 authentication script — generates a refresh token for Gmail API.

Usage:
    uv run python scripts/auth.py

Reads GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET from .env,
runs the OAuth2 flow in the browser, and writes GMAIL_REFRESH_TOKEN back to .env.
"""

import os
import re
from pathlib import Path

from dotenv import load_dotenv
from google_auth_oauthlib.flow import InstalledAppFlow

SCOPES = ["https://www.googleapis.com/auth/gmail.modify"]
ENV_PATH = Path(__file__).resolve().parent.parent / ".env"


def main() -> None:
    load_dotenv(ENV_PATH)

    client_id = os.environ.get("GMAIL_CLIENT_ID")
    client_secret = os.environ.get("GMAIL_CLIENT_SECRET")
    if not client_id or not client_secret:
        print("ERROR: GMAIL_CLIENT_ID and GMAIL_CLIENT_SECRET must be set in .env")
        return

    client_config = {
        "installed": {
            "client_id": client_id,
            "client_secret": client_secret,
            "auth_uri": "https://accounts.google.com/o/oauth2/auth",
            "token_uri": "https://oauth2.googleapis.com/token",
        }
    }

    flow = InstalledAppFlow.from_client_config(client_config, SCOPES)
    creds = flow.run_local_server(port=0)
    refresh_token = creds.refresh_token

    print(f"Refresh token obtained: {refresh_token[:20]}...")

    # Update .env file
    env_content = ENV_PATH.read_text() if ENV_PATH.exists() else ""
    if re.search(r"^GMAIL_REFRESH_TOKEN=", env_content, re.MULTILINE):
        env_content = re.sub(
            r"^GMAIL_REFRESH_TOKEN=.*$",
            f"GMAIL_REFRESH_TOKEN={refresh_token}",
            env_content,
            flags=re.MULTILINE,
        )
    else:
        env_content = env_content.rstrip() + f"\nGMAIL_REFRESH_TOKEN={refresh_token}\n"

    ENV_PATH.write_text(env_content)
    print(f"Refresh token saved to {ENV_PATH}")


if __name__ == "__main__":
    main()
