"""Unit tests for the shared conftest fixtures added/reshaped by the rcust restructure (P2d/P4):
`op_state` (run-scoped op context from $CCCI_OP_STATE_FILE) and `deps` (consolidated dep creds
with attribute sugar). Pure — exercised via request.getfixturevalue with env monkeypatched."""

from __future__ import annotations

import json

import pytest


def test_op_state_fixture_reads_file(tmp_path, monkeypatch, request):
    f = tmp_path / "op.json"
    f.write_text(json.dumps({"backup": {"snapshot_id": "abc123"}, "upgrade": {"head_ref": "h"}}))
    monkeypatch.setenv("CCCI_OP_STATE_FILE", str(f))
    st = request.getfixturevalue("op_state")
    assert st["backup"]["snapshot_id"] == "abc123"
    assert st["upgrade"]["head_ref"] == "h"


def test_op_state_fixture_skips_without_env(monkeypatch, request):
    monkeypatch.delenv("CCCI_OP_STATE_FILE", raising=False)
    with pytest.raises(pytest.skip.Exception, match="orchestrator"):
        request.getfixturevalue("op_state")


def test_op_state_fixture_skips_on_missing_file(tmp_path, monkeypatch, request):
    monkeypatch.setenv("CCCI_OP_STATE_FILE", str(tmp_path / "nope.json"))
    with pytest.raises(pytest.skip.Exception, match="missing"):
        request.getfixturevalue("op_state")


def test_deps_fixture_entries_expose_attributes(tmp_path, monkeypatch, request):
    """`deps` (session-scoped) coerces the run deps file into entries with .domain/.realm/...
    attribute sugar while keeping dict-style access (rcust P2d). Single test for the session-
    cached fixture (one instantiation)."""
    f = tmp_path / "deps.json"
    f.write_text(
        json.dumps(
            {"keycloak": {"recipe": "keycloak", "domain": "kc.x", "client_secret": "s3cret"}}
        )
    )
    monkeypatch.setenv("CCCI_DEPS_FILE", str(f))
    deps = request.getfixturevalue("deps")
    assert deps["keycloak"].domain == "kc.x"
    assert deps["keycloak"]["client_secret"] == "s3cret"
    with pytest.raises(AttributeError):
        _ = deps["keycloak"].not_a_field
