import httpx
from fastapi.testclient import TestClient

from app import task_store
from app.main import app, get_pulp_client

client = TestClient(app)


class _FakePulp:
    def __init__(self, repo=None, task=None, sync_raises=False):
        self._repo = (
            {"remote": "/pulp/api/v3/remotes/rpm/rpm/r1/"} if repo is None else repo
        )
        self._task = task
        self._sync_raises = sync_raises
        self.synced = None

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

    def sync_repo(self, uuid, remote_href):
        if self._sync_raises:
            raise httpx.ConnectError("connection refused")
        self.synced = (uuid, remote_href)
        return f"/pulp/api/v3/tasks/t-{uuid}/"

    def get_task(self, task_href):
        return self._task


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


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


def test_start_sync_begins_polling_and_records_task():
    fake = _FakePulp()
    _use(fake)
    resp = client.post("/repos/abc/sync")
    assert resp.status_code == 200
    assert 'hx-get="/repos/abc/progress"' in resp.text
    assert 'hx-trigger="every 3s"' in resp.text
    assert task_store.get_task("abc") == "/pulp/api/v3/tasks/t-abc/"
    assert fake.synced == ("abc", "/pulp/api/v3/remotes/rpm/rpm/r1/")


def test_start_sync_without_remote_is_rejected():
    _use(_FakePulp(repo={}))  # remote 미설정
    resp = client.post("/repos/abc/sync")
    assert resp.status_code == 400
    assert "remote" in resp.text
    assert task_store.get_task("abc") is None


def test_start_sync_handles_pulp_error():
    _use(_FakePulp(sync_raises=True))
    resp = client.post("/repos/abc/sync")
    assert resp.status_code == 502
    assert "동기화 시작 실패" in resp.text
    assert task_store.get_task("abc") is None


def test_progress_running_renders_bar_and_keeps_polling():
    task_store.set_task("abc", "/pulp/api/v3/tasks/t1/")
    _use(
        _FakePulp(
            task={"state": "running", "progress_reports": [{"done": 4, "total": 8}]}
        )
    )
    resp = client.get("/repos/abc/progress")
    assert resp.status_code == 200
    assert "50%" in resp.text
    assert 'hx-trigger="every 3s"' in resp.text
    assert task_store.get_task("abc") is not None  # 아직 추적 중


def test_progress_completed_stops_polling_and_clears():
    task_store.set_task("abc", "/pulp/api/v3/tasks/t1/")
    _use(
        _FakePulp(
            task={
                "state": "completed",
                "created_resources": [
                    "/pulp/api/v3/repositories/rpm/rpm/abc/versions/7/"
                ],
            }
        )
    )
    resp = client.get("/repos/abc/progress")
    assert "완료" in resp.text
    assert "v7" in resp.text
    assert "hx-trigger" not in resp.text  # 폴링 중단
    assert task_store.get_task("abc") is None  # 정리됨


def test_progress_failed_shows_error_and_clears():
    task_store.set_task("abc", "/pulp/api/v3/tasks/t1/")
    _use(_FakePulp(task={"state": "failed", "error": {"description": "GPG 검증 실패"}}))
    resp = client.get("/repos/abc/progress")
    assert "동기화 실패" in resp.text
    assert "GPG 검증 실패" in resp.text
    assert "hx-trigger" not in resp.text
    assert task_store.get_task("abc") is None


def test_progress_idle_when_no_active_task():
    _use(_FakePulp())
    resp = client.get("/repos/zzz/progress")
    assert resp.status_code == 200
    assert "hx-trigger" not in resp.text  # 폴링하지 않음
