"""Integration tests for v3.6 layer-0 task md sha contract (fixture-driven).

chair_authorization_id=CHAIR-AUTH-TASK-2705PLUS1-V36-TASK-MD-SHA-BOOTSTRAP-260528
"""
from __future__ import annotations

import sys
sys.path.insert(0, "/home/jay/workspace")

import base64
import json
import os
from pathlib import Path
from typing import Any, Dict

import pytest

from scripts.harness.v36.task_md_sha_contract import (
    DECISION_ALLOW,
    classify,
    measure_sha_file,
)
from scripts.harness.v36.task_md_sha_marker_writer import write_task_md_sha_marker

FIXTURE_DIR = Path(__file__).parent / "fixtures"
FIXTURE_PREFIX = "v36_task_md_sha_"

_FIXTURE_FILES = sorted(
    [
        p.name
        for p in FIXTURE_DIR.glob(FIXTURE_PREFIX + "*.json")
        if p.name.startswith(FIXTURE_PREFIX)
    ]
)


def _b64_to_bytes(value: Any) -> Any:
    if value is None:
        return None
    return base64.b64decode(value)


def _load_fixture(name: str) -> Dict[str, Any]:
    with open(FIXTURE_DIR / name, "r", encoding="utf-8") as fh:
        return json.load(fh)


@pytest.mark.parametrize("fixture_name", _FIXTURE_FILES)
def test_fixture_classify(fixture_name: str) -> None:
    fixture = _load_fixture(fixture_name)
    inputs = fixture["inputs"]
    expected = fixture["expected_decision"]

    result = classify(
        pre_sha=inputs.get("dispatch_pre_sha"),
        post_sha=inputs.get("dispatch_post_sha"),
        observed_sha=inputs.get("executor_observed_sha"),
        pre_content=_b64_to_bytes(inputs.get("pre_content_b64")),
        post_content=_b64_to_bytes(inputs.get("post_content_b64")),
        observed_content=_b64_to_bytes(inputs.get("observed_content_b64")),
    )

    for key in (
        "patch_type",
        "content_verbatim_match",
        "continue_allowed",
        "decision_class",
        "mismatch_location",
    ):
        assert (
            result[key] == expected[key]
        ), f"{fixture_name} {key} mismatch: got {result[key]!r}, expected {expected[key]!r}"


def test_task_2705_replay_yields_allow() -> None:
    fixture = _load_fixture("v36_task_md_sha_replay_task_2705_1byte_strip.json")
    inputs = fixture["inputs"]
    result = classify(
        pre_sha=inputs.get("dispatch_pre_sha"),
        post_sha=inputs.get("dispatch_post_sha"),
        observed_sha=inputs.get("executor_observed_sha"),
        pre_content=_b64_to_bytes(inputs.get("pre_content_b64")),
        post_content=_b64_to_bytes(inputs.get("post_content_b64")),
        observed_content=_b64_to_bytes(inputs.get("observed_content_b64")),
    )
    assert result["decision_class"] == DECISION_ALLOW
    assert result["patch_type"] == "WHITESPACE_NORMALIZATION"
    assert result["content_verbatim_match"] == "true"
    assert result["continue_allowed"] == "true"


def test_measure_sha_file_existing(tmp_path: Path) -> None:
    p = tmp_path / "x.md"
    p.write_bytes(b"hello world\n")
    sha, size, content = measure_sha_file(str(p))
    assert sha is not None and len(sha) == 64
    assert size == 12
    assert content == b"hello world\n"


def test_measure_sha_file_missing() -> None:
    sha, size, content = measure_sha_file("/nonexistent/path.md")
    assert sha is None and size is None and content is None


def test_marker_writer_safe_fail(tmp_path: Path) -> None:
    """Writer must produce a 14-field JSON file matching the schema."""
    marker_path = write_task_md_sha_marker(
        task_id="task-test-1",
        dispatch_pre_sha="abc",
        dispatch_post_sha="def",
        executor_observed_sha="def",
        classification={
            "patch_type": "NO_PATCH",
            "content_verbatim_match": "true",
            "continue_allowed": "true",
            "decision_class": "ALLOW",
            "reason_code": "post_observed_match_allow",
            "mismatch_location": "UNKNOWN",
        },
        chair_authorization_id="CHAIR-TEST",
        events_dir=str(tmp_path),
    )
    assert marker_path is not None
    assert os.path.exists(marker_path)
    with open(marker_path, "r", encoding="utf-8") as fh:
        marker = json.load(fh)
    assert marker["schema_version"] == "v36.task_md_sha_decision.v1"
    assert marker["task_id"] == "task-test-1"
    assert marker["shas"] == {
        "dispatch_pre_sha": "abc",
        "dispatch_post_sha": "def",
        "executor_observed_sha": "def",
    }
    assert marker["chair_authorization_id"] == "CHAIR-TEST"


def test_fixture_files_exist() -> None:
    """Make sure all required fixtures are present."""
    required = [
        "v36_task_md_sha_fixture_1_allow_no_patch.json",
        "v36_task_md_sha_fixture_2_allow_sidecar.json",
        "v36_task_md_sha_fixture_3_allow_retry_header.json",
        "v36_task_md_sha_fixture_4_allow_whitespace.json",
        "v36_task_md_sha_fixture_5_hold_unverifiable.json",
        "v36_task_md_sha_fixture_6_deny_semantic_change.json",
        "v36_task_md_sha_fixture_7_deny_forbidden_change.json",
        "v36_task_md_sha_fixture_8_e2e_integration.json",
        "v36_task_md_sha_replay_task_2705_1byte_strip.json",
    ]
    for name in required:
        assert (FIXTURE_DIR / name).exists(), f"Missing fixture: {name}"


if __name__ == "__main__":  # pragma: no cover
    pytest.main([__file__, "-v"])
