"""task md sha256 immutability 검증 회귀 테스트."""

from __future__ import annotations

import hashlib
import os as _os
import sys as _sys
from pathlib import Path

_WROOT = _os.path.dirname(
    _os.path.dirname(_os.path.dirname(_os.path.dirname(_os.path.abspath(__file__))))
)
if _WROOT in _sys.path:
    _sys.path.remove(_WROOT)
_sys.path.insert(0, _WROOT)

from utils.task_mode_classifier import (  # type: ignore[reportMissingImports] # noqa: E402
    MUTATION_FORBIDDEN_MARKER,
    check_task_md_immutability,
)


def _write(tmp_path: Path, name: str, body: str) -> str:
    p = tmp_path / name
    p.write_text(body, encoding="utf-8")
    return str(p)


def test_sha256_unchanged_when_recorded_matches(tmp_path: Path) -> None:
    body = "# task md\n\n원본 내용입니다.\n"
    md = _write(tmp_path, "task.md", body)
    recorded = hashlib.sha256(body.encode("utf-8")).hexdigest()

    is_unchanged, current = check_task_md_immutability(md, recorded)
    assert is_unchanged is True
    assert current == recorded


def test_sha256_changed_when_content_modified(tmp_path: Path) -> None:
    body = "# task md\n\nv1 내용.\n"
    md = _write(tmp_path, "task.md", body)
    recorded = hashlib.sha256(body.encode("utf-8")).hexdigest()

    # post-dispatch mutation 발생
    Path(md).write_text("# task md\n\nv2 내용으로 변경됨.\n", encoding="utf-8")

    is_unchanged, current = check_task_md_immutability(md, recorded)
    assert is_unchanged is False
    assert current != recorded
    assert len(current) == 64  # sha256 hex


def test_recorded_none_returns_true(tmp_path: Path) -> None:
    md = _write(tmp_path, "task.md", "# 초기 기록용 task md\n")

    is_unchanged, current = check_task_md_immutability(md, None)
    assert is_unchanged is True
    assert len(current) == 64


def test_mutation_forbidden_marker_constant() -> None:
    assert MUTATION_FORBIDDEN_MARKER == "TASK_MD_POST_DISPATCH_MUTATION_FORBIDDEN"
