import httpx
from fastapi.testclient import TestClient

from app.main import app, get_pulp_client

client = TestClient(app)

REPO = {"name": "rocky9-baseos", "repo_config": {"gpgcheck": 1, "repo-gpgcheck": 1}}
VERSIONS = [
    {
        "pulp_href": "/pulp/api/v3/repositories/rpm/rpm/abc/versions/1/",
        "pulp_created": "2026-05-01T00:00:00Z",
        "content_summary": {"present": {"rpm.package": {"count": 100}}},
    },
    {
        "pulp_href": "/pulp/api/v3/repositories/rpm/rpm/abc/versions/2/",
        "pulp_created": "2026-06-01T00:00:00Z",
        "content_summary": {"present": {"rpm.package": {"count": 150}}},
    },
]
# v2 가 배포 중: distribution → publication → repository_version v2
DISTRIBUTIONS = [{"publication": "/pulp/api/v3/publications/rpm/rpm/p1/"}]
PUBLICATIONS = {
    "/pulp/api/v3/publications/rpm/rpm/p1/": {
        "repository_version": "/pulp/api/v3/repositories/rpm/rpm/abc/versions/2/"
    }
}


class _FakePulp:
    def __init__(
        self,
        repo=None,
        versions=None,
        distributions=None,
        publications=None,
        versions_raises=False,
    ):
        self._repo = REPO if repo is None else repo
        self._versions = VERSIONS if versions is None else versions
        self._distributions = DISTRIBUTIONS if distributions is None else distributions
        self._publications = PUBLICATIONS if publications is None else publications
        self._versions_raises = versions_raises

    def get_repo(self, uuid):
        return self._repo

    def list_versions(self, uuid):
        if self._versions_raises:
            raise httpx.ConnectError("down")
        return self._versions

    def list_distributions(self):
        return self._distributions

    def get_publication(self, href):
        return self._publications.get(href, {})


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


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


def test_versions_page_lists_newest_first():
    _use(_FakePulp())
    resp = client.get("/repos/abc/versions")
    assert resp.status_code == 200
    body = resp.text
    assert "rocky9-baseos" in body
    assert "v1" in body and "v2" in body
    # 최신순: v2 가 v1 보다 먼저 나온다
    assert body.index("v2") < body.index("v1")


def test_versions_page_marks_deployed_version():
    _use(_FakePulp())
    body = client.get("/repos/abc/versions").text
    assert "운영 배포 중" in body
    # 배포 중이 아닌 v1 에는 배포 버튼(비활성)이 있다
    assert "이 버전 배포" in body


def test_versions_page_no_deployed_when_no_distribution():
    _use(_FakePulp(distributions=[]))
    body = client.get("/repos/abc/versions").text
    assert "운영 배포 중" not in body


def test_versions_page_shows_verification_detail():
    _use(_FakePulp())
    body = client.get("/repos/abc/versions").text
    assert "검증됨" in body
    assert "gpgcheck=1" in body


def test_versions_page_error_when_list_fails():
    _use(_FakePulp(versions_raises=True))
    resp = client.get("/repos/abc/versions")
    assert resp.status_code == 200
    assert "불러오지 못했습니다" in resp.text
