from __future__ import annotations

from types import SimpleNamespace

import autodebug.doctor as doctor


def test_auto_link_project_read_only_lookup_match(monkeypatch):
    monkeypatch.setattr(doctor, "_detect_repo_slug", lambda: "org/repo")

    class FakeResponse:
        status_code = 200

        @staticmethod
        def json():
            return [{"id": "proj_123", "repo": "org/repo"}]

    called = {"get": 0}

    def fake_get(*args, **kwargs):
        called["get"] += 1
        return FakeResponse()

    monkeypatch.setattr(doctor.requests, "get", fake_get)

    pid, reason = doctor._auto_link_project({"api_base": "https://example.test"}, "token")
    assert pid == "proj_123"
    assert reason is None
    assert called["get"] == 1


def test_auto_link_project_read_only_no_match(monkeypatch):
    monkeypatch.setattr(doctor, "_detect_repo_slug", lambda: "org/repo")

    class FakeResponse:
        status_code = 200

        @staticmethod
        def json():
            return [{"id": "proj_other", "repo": "org/other"}]

    monkeypatch.setattr(doctor.requests, "get", lambda *a, **k: FakeResponse())

    pid, reason = doctor._auto_link_project({"api_base": "https://example.test"}, "token")
    assert pid is None
    assert "No matching project found" in (reason or "")


def test_check_credentials_uses_project_lookup_failed_text(monkeypatch):
    monkeypatch.setattr(doctor, "load_credentials", lambda: {"project_id": None})

    # Patch imported function inside check_credentials.
    import autodebug.config as cfg
    monkeypatch.setattr(cfg, "get_valid_token", lambda: "token")

    monkeypatch.setattr(doctor, "_auto_link_project", lambda creds, token: (None, "Project lookup failed (500)"))

    result = doctor.check_credentials()
    assert result.name == "credentials"
    assert result.passed is False
    assert "No project configured" in result.message
    assert "Project lookup failed:" in (result.detail or "")
