from __future__ import annotations

import datetime as dt
import os
from tempfile import NamedTemporaryFile

import worai.seoreport.core as core
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)


def test_generate_report_skips_inspection_when_limit_zero(monkeypatch):
    date = dt.date(2026, 1, 1)

    def build_period(name: str) -> core.PeriodAnalysis:
        ranges = core.PeriodRanges(
            current=core.DateRange(date, date),
            pop=core.DateRange(date, date),
            yoy=core.DateRange(date, date),
        )
        return core.PeriodAnalysis(
            name=name,
            dates=ranges,
            overall={},
            winning=[],
            losing=[],
            opportunities=[],
            daily_trend=[],
        )

    def fake_run_tasks(tasks, max_workers):
        return {
            "7": build_period("Last 7 days"),
            "30": build_period("Last 30 days"),
            "90": build_period("Last 90 days"),
        }

    def fail_fetch(*args, **kwargs):
        raise AssertionError("fetch_gsc_data should not be called when inspect_limit <= 0")

    monkeypatch.setattr(core, "_run_tasks", fake_run_tasks)
    monkeypatch.setattr(core, "fetch_gsc_data", fail_fetch)
    monkeypatch.setattr(core, "load_credentials", lambda *args, **kwargs: object())
    monkeypatch.setattr(core, "AuthorizedSession", lambda creds: object())
    monkeypatch.setattr(core, "find_last_available_date", lambda session, site: date)

    options = core.ReportOptions(
        site="sc-domain:example.com",
        client_secrets=None,
        token="oauth_token.json",
        inspect_limit=0,
        ga_id=None,
    )

    data = core.generate_report_data(options)
    assert data["indexing"].sample_size == 0
    assert data["health"].total_checked == 0
