from __future__ import annotations

import os
from tempfile import NamedTemporaryFile

from worai.seoreport.core import _resolve_ga_auth, _run_tasks, ReportOptions


def test_run_tasks_collects_results():
    tasks = [
        ("a", lambda: 1),
        ("b", lambda: 2),
        ("c", lambda: 3),
    ]
    results = _run_tasks(tasks, max_workers=2)
    assert results == {"a": 1, "b": 2, "c": 3}


def test_resolve_ga_auth_uses_token_when_no_client_secrets():
    with NamedTemporaryFile() as tmp:
        options = ReportOptions(
            site="sc-domain:example.com",
            client_secrets=None,
            token=tmp.name,
            ga_id="123456789",
            ga_client_secrets=None,
            ga_token=None,
        )
        secrets, token_path = _resolve_ga_auth(options)
        assert secrets is None
        assert token_path == tmp.name


def test_resolve_ga_auth_requires_secret_when_no_token():
    options = ReportOptions(
        site="sc-domain:example.com",
        client_secrets=None,
        token="does-not-exist.json",
        ga_id="123456789",
        ga_client_secrets=None,
        ga_token="does-not-exist.json",
    )
    if os.path.exists(options.token):
        os.remove(options.token)
    try:
        _resolve_ga_auth(options)
        assert False, "expected RuntimeError"
    except RuntimeError as exc:
        assert "GA client secrets path is required" in str(exc)
