# retoor <retoor@molodetz.nl>

import types

from devplacepy.services.bot.bot import DevPlaceBot
from devplacepy.services.bot.config import HOME_URL
from tests.conftest import run_async


def _fake_bot(profile, profile_filled=True, update_ok=True):
    fake = types.SimpleNamespace()
    fake.state = types.SimpleNamespace(profile_filled=profile_filled)
    fake.logs = []
    fake.updates = 0
    fake.base_url = "http://localhost:10500"

    async def _fetch():
        return profile

    async def _update():
        fake.updates += 1
        return update_ok

    async def _goto(url):
        return None

    async def _idle(*args):
        return None

    fake._fetch_own_profile = _fetch
    fake._profile_has_signal = lambda: DevPlaceBot._profile_has_signal(fake)
    fake._update_profile = _update
    fake._log = lambda msg: fake.logs.append(msg)
    fake.b = types.SimpleNamespace(goto=_goto, _idle=_idle)
    return fake


def _profile(bio, website):
    return {"profile_user": {"bio": bio, "website": website}}


def test_profile_has_signal_accepts_signalled_bio_and_home_website():
    fake = _fake_bot(_profile(f"Grown at {HOME_URL}.", HOME_URL))
    assert run_async(DevPlaceBot._profile_has_signal(fake)) is True


def test_profile_has_signal_rejects_plain_bio():
    fake = _fake_bot(_profile("Just a developer.", HOME_URL))
    assert run_async(DevPlaceBot._profile_has_signal(fake)) is False


def test_profile_has_signal_rejects_foreign_website():
    fake = _fake_bot(_profile(f"Grown at {HOME_URL}.", "https://example.dev"))
    assert run_async(DevPlaceBot._profile_has_signal(fake)) is False


def test_profile_has_signal_rejects_empty_profile():
    fake = _fake_bot({})
    assert run_async(DevPlaceBot._profile_has_signal(fake)) is False


def test_ensure_profile_signal_skips_update_when_already_signalled():
    fake = _fake_bot(_profile(f"Grown at {HOME_URL}.", HOME_URL))
    assert run_async(DevPlaceBot._ensure_profile_signal(fake)) is True
    assert fake.updates == 0


def test_ensure_profile_signal_updates_when_signal_missing():
    fake = _fake_bot(_profile("Just a developer.", HOME_URL))
    assert run_async(DevPlaceBot._ensure_profile_signal(fake)) is True
    assert fake.updates == 1


def test_ensure_profile_signal_updates_unfilled_profile():
    fake = _fake_bot(_profile(f"Grown at {HOME_URL}.", HOME_URL), profile_filled=False)
    assert run_async(DevPlaceBot._ensure_profile_signal(fake)) is True
    assert fake.updates == 1


def test_ensure_profile_signal_reports_failed_update():
    fake = _fake_bot(_profile("Just a developer.", HOME_URL), update_ok=False)
    assert run_async(DevPlaceBot._ensure_profile_signal(fake)) is False
    assert fake.updates == 1
