"""Tests for pilot-readiness kyverno-json policies (REQ-320, v1.26 P3 W4).

Tests the policy in adapters/kyverno-json/policies/pilot-readiness/:
no-placeholder-account. The payload is the env JSON shape
(core/environments/<env>.json): asserts account_id != "000000000000".
Runs against real ``kj`` (not skipped) — the W0.5 fix installed the
binary and unmasked the v1.25 substrate bugs.
"""

import json
import os
import sys
from pathlib import Path

import pytest

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import importlib.util
_ENGINE_PATH = Path(__file__).resolve().parent.parent / "adapters" / "kyverno-json" / "kyverno_json_engine.py"
_spec = importlib.util.spec_from_file_location("kyverno_json_engine", _ENGINE_PATH)
_mod = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(_mod)
KyvernoJsonEngine = _mod.KyvernoJsonEngine

POLICY_DIR = Path(__file__).resolve().parent.parent / "adapters" / "kyverno-json" / "policies" / "pilot-readiness"
FIXTURES = Path(__file__).resolve().parent / "fixtures" / "pilot_readiness"


def _kj_installed() -> bool:
    return _mod._which_kj() is not None


@pytest.fixture(autouse=True)
def _require_kj():
    if not _kj_installed():
        pytest.skip("kj not installed (scripts/install-kyverno-json.sh)")


def _load(name):
    with open(FIXTURES / name, "r", encoding="utf-8") as fh:
        return json.load(fh)


class TestPassingFixture:
    def test_real_account_passes(self):
        eng = KyvernoJsonEngine()
        out = eng.evaluate(_load("real_account.json"), POLICY_DIR, "cid-pass")
        assert isinstance(out, list)
        assert len(out) >= 1
        fails = [p for p in out if p["result"] == "fail"]
        assert fails == [], f"expected no fails on real_account fixture, got: {fails}"


class TestFailingFixture:
    def test_placeholder_account_fails(self):
        eng = KyvernoJsonEngine()
        out = eng.evaluate(_load("placeholder_account.json"), POLICY_DIR, "cid-fail")
        fails = [p for p in out if p["result"] == "fail"]
        assert len(fails) >= 1, "expected at least one fail on the placeholder_account fixture"


class TestPolicyFilesExist:
    def test_policy_present(self):
        files = sorted(os.listdir(POLICY_DIR))
        assert "no-placeholder-account.json" in files


class TestPolicyValidity:
    def test_policy_is_valid_json(self):
        for f in os.listdir(POLICY_DIR):
            if f.endswith(".json"):
                with open(POLICY_DIR / f, "r", encoding="utf-8") as fh:
                    data = json.load(fh)
                assert data["apiVersion"] == "json.kyverno.io/v1alpha1"
                assert data["kind"] == "ValidatingPolicy"
                assert "nova.cloudinit.dev/severity" in data["metadata"]["annotations"]

    def test_policy_name_matches_filename(self):
        for f in os.listdir(POLICY_DIR):
            if f.endswith(".json"):
                with open(POLICY_DIR / f, "r", encoding="utf-8") as fh:
                    data = json.load(fh)
                expected = f.rsplit(".", 1)[0]
                assert data["metadata"]["name"] == expected