"""Tests for Phase 11.H — API v2 stub + lifecycle hooks."""

from __future__ import annotations

import pytest
from django.test import Client

from simorgh.core.hooks import (
    HookError,
    clear_hooks,
    register_hook,
    registered_hooks,
    run_hook,
)

# ---------------------------------------------------------------------------
# API v2
# ---------------------------------------------------------------------------


@pytest.mark.django_db
def test_api_v2_root_returns_version_metadata(alice, tenant_acme):
    client = Client(HTTP_X_TENANT=tenant_acme.slug)
    client.force_login(alice)
    resp = client.get("/api/v2/")
    assert resp.status_code == 200
    body = resp.json()
    assert body["version"] == "v2"
    assert body["status"] == "preview"


# ---------------------------------------------------------------------------
# Lifecycle hooks
# ---------------------------------------------------------------------------


HOOK = "test.phase11.demo_hook"


@pytest.fixture(autouse=True)
def _clean_hooks():
    yield
    clear_hooks(HOOK)


def test_register_and_run_hook_collects_results():
    @register_hook(HOOK)
    def h1(x):
        return x + 1

    @register_hook(HOOK)
    def h2(x):
        return x * 2

    results = run_hook(HOOK, 5)
    assert results == [6, 10]


def test_priority_orders_execution():
    order: list[str] = []

    @register_hook(HOOK, priority=200)
    def late():
        order.append("late")

    @register_hook(HOOK, priority=50)
    def early():
        order.append("early")

    run_hook(HOOK)
    assert order == ["early", "late"]


def test_hook_error_propagates_and_aborts_chain():
    calls: list[str] = []

    @register_hook(HOOK, priority=10)
    def veto():
        calls.append("veto")
        raise HookError("nope")

    @register_hook(HOOK, priority=20)
    def never():
        calls.append("never")

    with pytest.raises(HookError):
        run_hook(HOOK)
    assert calls == ["veto"]


def test_run_hook_with_no_handlers_returns_empty_list():
    assert run_hook("test.phase11.unknown_hook") == []


def test_registered_hooks_reports_handler_counts():
    @register_hook(HOOK)
    def h():
        pass

    snapshot = registered_hooks()
    assert snapshot.get(HOOK) == 1


def test_clear_hooks_removes_specific_name():
    @register_hook(HOOK)
    def h():
        pass

    clear_hooks(HOOK)
    assert run_hook(HOOK) == []
