"""anu_normal_callback_envelope_v1 JSON Schema 회귀 테스트 (task-2694+1 MT-6).

회장 verbatim ANCHOR-2: task-2693 envelope 에서
``schedule_type=to_be_registered_by_finish_task_sh`` 어구로 deferred 우회가
발생했다. 본 schema 는 enum 화이트리스트를 통해 정적 단계에서 reject 한다.
"""

from __future__ import annotations

import json
import os

import pytest

jsonschema = pytest.importorskip("jsonschema")


SCHEMA_PATH = os.path.join(
    os.path.dirname(__file__),
    "..",
    "..",
    "..",
    "schemas",
    "anu_normal_callback_envelope_v1.json",
)
SCHEMA_PATH = os.path.abspath(SCHEMA_PATH)


@pytest.fixture(scope="module")
def schema():
    with open(SCHEMA_PATH, "r", encoding="utf-8") as fp:
        return json.load(fp)


def _base_payload() -> dict:
    return {
        "schema": "schemas.anu_normal_callback_envelope_v1",
        "task_id": "task-2694+1",
        "schedule_id": "sid-1",
        "schedule_type": "cron_once",
        "owner_key": "c119085addb0f8b7",
        "chat_id": "6937032012",
        "chair_facing_sid": "53e89540-5bed-4692-a726-ed857820758a",
        "emitted_at": "2026-05-27T00:00:00Z",
    }


def test_schema_file_exists():
    """schema 파일이 worktree 에 박제되어 있어야 함."""
    assert os.path.isfile(SCHEMA_PATH), f"schema missing at {SCHEMA_PATH}"


def test_valid_payload_accepted(schema):
    """allow-listed schedule_type 은 schema 통과."""
    jsonschema.validate(_base_payload(), schema)


@pytest.mark.parametrize(
    "blocked_type",
    [
        "to_be_registered_by_finish_task_sh",
        "deferred",
        "pending",
    ],
)
def test_blocked_schedule_type_rejected(schema, blocked_type):
    """task-2693 사고 박제 어구 — 정적 schema 단계에서 즉시 reject."""
    p = _base_payload()
    p["schedule_type"] = blocked_type
    with pytest.raises(jsonschema.ValidationError):
        jsonschema.validate(p, schema)


@pytest.mark.parametrize(
    "allowed_type",
    [
        "cron_once",
        "cron_recurring",
        "absolute_one_time",
    ],
)
def test_allowed_schedule_types_accepted(schema, allowed_type):
    """화이트리스트 schedule_type 3종 모두 통과해야 함."""
    p = _base_payload()
    p["schedule_type"] = allowed_type
    jsonschema.validate(p, schema)


def test_missing_required_field_rejected(schema):
    """required field (chair_facing_sid 등) 결손은 schema reject."""
    p = _base_payload()
    del p["chair_facing_sid"]
    with pytest.raises(jsonschema.ValidationError):
        jsonschema.validate(p, schema)


def test_owner_key_pattern_enforced(schema):
    """owner_key 는 16-char lowercase hex 만 허용."""
    p = _base_payload()
    p["owner_key"] = "NOT_HEX"
    with pytest.raises(jsonschema.ValidationError):
        jsonschema.validate(p, schema)
