import sys
from pathlib import Path

PROJECT_ROOT = Path(__file__).resolve().parents[1]
if str(PROJECT_ROOT) not in sys.path:
    sys.path.insert(0, str(PROJECT_ROOT))

from services import social_login
from services.social_login import normalize_social_endpoint, parse_space_scan_page, poll_social_scan


def test_normalize_social_endpoint_accepts_space_root():
    assert normalize_social_endpoint("") == "https://www.spacezs.cn/connect.php"
    assert normalize_social_endpoint("https://www.spacezs.cn/") == "https://www.spacezs.cn/connect.php"
    assert normalize_social_endpoint("https://www.spacezs.cn") == "https://www.spacezs.cn/connect.php"


def test_parse_space_scan_page_extracts_qr_and_state():
    html = 'var qrcode_url = "http://weixin.qq.com/q/test"; var state = "state-123";'
    assert parse_space_scan_page(html) == ("http://weixin.qq.com/q/test", "state-123")


def test_poll_social_scan_treats_code_zero_as_authorized(monkeypatch):
    class FakeResponse:
        def json(self):
            return {"code": 0, "url": "https://zsglpt.workyai.cn/login?type=wx&code=ok"}

    def fake_get(*_args, **_kwargs):
        return FakeResponse()

    monkeypatch.setattr(social_login.requests, "get", fake_get)
    monkeypatch.setattr(social_login, "social_appkey", lambda _cfg: "key")

    result = poll_social_scan(
        {
            "social_login_enabled": 1,
            "social_login_endpoint": "https://www.spacezs.cn/connect.php",
            "social_login_appid": "appid",
            "social_login_appkey": "encrypted",
            "social_login_providers": "wx",
        },
        provider="wx",
        state="state-123",
    )

    assert result == {"status": "authorized", "url": "https://zsglpt.workyai.cn/login?type=wx&code=ok"}
