from __future__ import annotations

from types import SimpleNamespace

import worai.core.gsc as gsc
import worai.seoreport.analytics as analytics


class _DummyCreds:
    def __init__(self):
        self.valid = True
        self.expired = False
        self.refresh_token = "refresh"
        self.scopes = []

    def to_json(self) -> str:
        return "{}"


def _make_flow(calls):
    def _from_client_secrets_file(path, scopes):
        def _run_local_server(**kwargs):
            calls.append(kwargs)
            return _DummyCreds()

        return SimpleNamespace(run_local_server=_run_local_server)

    return _from_client_secrets_file


def test_ga_oauth_requests_offline_refresh(monkeypatch, tmp_path):
    calls: list[dict] = []
    monkeypatch.setattr(
        analytics.InstalledAppFlow,
        "from_client_secrets_file",
        _make_flow(calls),
    )

    token_path = tmp_path / "ga_token.json"
    analytics.load_ga_credentials("client_secrets.json", str(token_path), port=8080)

    assert calls, "Expected OAuth flow to run"
    assert calls[0]["access_type"] == "offline"
    assert calls[0]["prompt"] == "consent"
    assert calls[0]["include_granted_scopes"] == "true"


def test_gsc_oauth_requests_offline_refresh(monkeypatch, tmp_path):
    calls: list[dict] = []
    monkeypatch.setattr(
        gsc.InstalledAppFlow,
        "from_client_secrets_file",
        _make_flow(calls),
    )

    token_path = tmp_path / "gsc_token.json"
    gsc.load_credentials("client_secrets.json", str(token_path), port=8080)

    assert calls, "Expected OAuth flow to run"
    assert calls[0]["access_type"] == "offline"
    assert calls[0]["prompt"] == "consent"
    assert calls[0]["include_granted_scopes"] == "true"
