"""OAuth2 authentication for Gmail API."""

import json
import os
from pathlib import Path

from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build

SCOPES = [
    "https://mail.google.com/",
]

TOKEN_FILE = Path.home() / ".gmailarchiver" / "token.json"
CREDS_FILE = Path.home() / ".gmailarchiver" / "credentials.json"


def get_service(credentials_path: Path | None = None, token_path: Path | None = None):
    """
    Authenticate and return an authorized Gmail API service.

    On first run, opens a browser for OAuth consent. Token is cached at
    ~/.gmailarchiver/token.json for subsequent runs.

    Args:
        credentials_path: Path to credentials.json from Google Cloud Console.
                          Defaults to ~/.gmailarchiver/credentials.json.
        token_path:        Where to cache the OAuth token.
                          Defaults to ~/.gmailarchiver/token.json.
    """
    creds_file = Path(credentials_path) if credentials_path else CREDS_FILE
    token_file = Path(token_path) if token_path else TOKEN_FILE

    token_file.parent.mkdir(parents=True, exist_ok=True)

    if not creds_file.exists():
        raise FileNotFoundError(
            f"credentials.json not found at {creds_file}.\n"
            "Download it from: https://console.cloud.google.com/apis/credentials\n"
            "Then place it at that path, or pass --credentials <path>."
        )

    creds = None
    if token_file.exists():
        creds = Credentials.from_authorized_user_file(str(token_file), SCOPES)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(str(creds_file), SCOPES)
            creds = flow.run_local_server(port=0)
        token_file.write_text(creds.to_json())

    return build("gmail", "v1", credentials=creds)
