import httpx
from fastapi.testclient import TestClient

from app.main import app, get_pulp_client

client = TestClient(app)

REPO = {
    "pulp_href": "/pulp/api/v3/repositories/rpm/rpm/abc-123/",
    "name": "rocky9-baseos",
    "latest_version_href": "/pulp/api/v3/repositories/rpm/rpm/abc-123/versions/2/",
    "repo_config": {"gpgcheck": 1, "repo-gpgcheck": 1},
}
VERSION = {
    "pulp_created": "2026-06-01T00:00:00Z",
    "content_summary": {"present": {"rpm.package": {"count": 1500}}},
}


class _FakePulp:
    def __init__(self, repos=None, version=None, fail=False):
        self._repos = repos or []
        self._version = version
        self._fail = fail

    def list_repos(self):
        if self._fail:
            raise httpx.ConnectError("connection refused")
        return self._repos

    def get_version(self, href):
        return self._version


def _use(fake):
    app.dependency_overrides[get_pulp_client] = lambda: fake


def teardown_function():
    app.dependency_overrides.clear()


def test_dashboard_lists_repos():
    _use(_FakePulp(repos=[REPO], version=VERSION))
    resp = client.get("/")
    assert resp.status_code == 200
    body = resp.text
    assert "rocky9-baseos" in body
    assert "v2" in body
    assert "1500" in body
    assert "검증됨" in body  # GPG pass 배지


def test_repos_fragment_standalone():
    _use(_FakePulp(repos=[REPO], version=VERSION))
    resp = client.get("/repos")
    assert resp.status_code == 200
    assert 'id="repo-list"' in resp.text
    assert "rocky9-baseos" in resp.text


def test_dashboard_empty():
    _use(_FakePulp(repos=[]))
    resp = client.get("/")
    assert resp.status_code == 200
    assert "등록된 저장소가 없습니다" in resp.text


def test_dashboard_shows_error_when_pulp_down():
    _use(_FakePulp(fail=True))
    resp = client.get("/")
    assert resp.status_code == 200  # 페이지는 뜨고 에러 메시지를 보여줌
    assert "불러오지 못했습니다" in resp.text


# --- 검색 / 정렬 / 페이지네이션 -------------------------------------------------

PASS = {"gpgcheck": 1, "repo-gpgcheck": 1}


class _ReposPulp:
    """specs: (name, package_count) 목록. 검증은 모두 pass, 버전 1."""

    def __init__(self, specs):
        self._repos = []
        self._counts = {}
        for i, (name, count) in enumerate(specs, start=1):
            href = f"/pulp/api/v3/repositories/rpm/rpm/{i:04d}/"
            vhref = f"{href}versions/1/"
            self._repos.append(
                {
                    "pulp_href": href,
                    "name": name,
                    "latest_version_href": vhref,
                    "repo_config": PASS,
                }
            )
            self._counts[vhref] = count

    def list_repos(self):
        return self._repos

    def get_version(self, href):
        return {
            "content_summary": {
                "present": {"rpm.package": {"count": self._counts.get(href, 0)}}
            }
        }


def test_repos_table_search_filters_by_name():
    _use(
        _ReposPulp(
            [("rocky9-baseos", 10), ("ubuntu2204-main", 20), ("rocky8-baseos", 30)]
        )
    )
    body = client.get("/repos/table", params={"q": "rocky"}).text
    assert "rocky9-baseos" in body
    assert "rocky8-baseos" in body
    assert "ubuntu2204-main" not in body


def test_repos_table_sort_by_packages_desc():
    _use(_ReposPulp([("alpha", 10), ("bravo", 300), ("charlie", 100)]))
    body = client.get("/repos/table", params={"sort": "packages", "dir": "desc"}).text
    # 패키지 많은 순: bravo(300) → charlie(100) → alpha(10)
    assert body.index("bravo") < body.index("charlie") < body.index("alpha")


def test_repos_table_paginates():
    specs = [(f"repo-{i:02d}", i) for i in range(1, 26)]  # 25개
    _use(_ReposPulp(specs))
    page1 = client.get(
        "/repos/table", params={"sort": "name", "dir": "asc", "page": 1}
    ).text
    page2 = client.get(
        "/repos/table", params={"sort": "name", "dir": "asc", "page": 2}
    ).text
    assert "repo-01" in page1 and "repo-20" in page1
    assert "repo-21" not in page1
    assert "repo-21" in page2 and "repo-25" in page2
    assert "1 / 2" in page1
