"""Shared Google OAuth helpers."""

from __future__ import annotations

import os

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

from worai.errors import UsageError

SHEETS_SCOPES = ["https://www.googleapis.com/auth/spreadsheets"]


def load_google_credentials(
    client_secrets_path: str | None,
    token_path: str,
    port: int,
    scopes: list[str],
) -> Credentials:
    previous_relax_scope = os.environ.get("OAUTHLIB_RELAX_TOKEN_SCOPE")
    os.environ["OAUTHLIB_RELAX_TOKEN_SCOPE"] = "1"

    creds = None
    try:
        if os.path.exists(token_path):
            try:
                creds = Credentials.from_authorized_user_file(token_path, scopes)
            except Exception:
                creds = None

        if creds and creds.scopes:
            missing = set(scopes) - set(creds.scopes)
            if missing:
                creds = None

        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        elif not creds or not creds.valid:
            if not client_secrets_path:
                raise UsageError(
                    "Google OAuth client secrets are required when token is missing "
                    "or lacks required scopes. Use --client-secrets or set gsc.client_secrets."
                )
            flow = InstalledAppFlow.from_client_secrets_file(client_secrets_path, scopes)
            creds = flow.run_local_server(
                port=port,
                access_type="offline",
                prompt="consent",
                include_granted_scopes="true",
            )

        with open(token_path, "w", encoding="utf-8") as handle:
            handle.write(creds.to_json())

        return creds
    finally:
        if previous_relax_scope is None:
            os.environ.pop("OAUTHLIB_RELAX_TOKEN_SCOPE", None)
        else:
            os.environ["OAUTHLIB_RELAX_TOKEN_SCOPE"] = previous_relax_scope
