#!/usr/bin/env python3
"""Regression tests for aria-deadline-reconcile.py fail-safe (KAR-684).

Run: python3 /root/aria/scripts/tests/test_deadline_reconcile.py
The module name has hyphens, so we load it via importlib.
"""
import importlib.util
import sys
import tempfile
from pathlib import Path

SCRIPT = Path("/root/aria/scripts/aria-deadline-reconcile.py")

spec = importlib.util.spec_from_file_location("dreconcile", SCRIPT)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)

START, END = mod.MARKER_START, mod.MARKER_END
PASS = "\033[32mPASS\033[0m"
FAIL = "\033[31mFAIL\033[0m"
results = []


def check(name, cond):
    results.append(cond)
    print(f"  [{PASS if cond else FAIL}] {name}")


def _tmpfile(body):
    fd, path = tempfile.mkstemp(suffix=".md")
    p = Path(path)
    p.write_text(body, encoding="utf-8")
    return p


# Case 1: markers present -> block replaced, file rewritten, backup made
body = f"header\n{START}\nOLD CONTENT\n{END}\nfooter\n"
p = _tmpfile(body)
try:
    changed = mod.atomic_replace_block(p, f"{START}\nNEW\n{END}")
    after = p.read_text(encoding="utf-8")
    check("case1: markers present -> rewrite", changed and "NEW" in after and "OLD CONTENT" not in after)
    check("case1: header/footer untouched", after.startswith("header") and after.rstrip().endswith("footer"))
    check("case1: backup created", any(b.name.startswith(p.name + ".bak.") for b in p.parent.glob(p.name + ".bak.*")))
finally:
    for b in p.parent.glob(p.name + ".bak.*"):
        b.unlink()
    p.unlink()

# Case 2: marker missing -> RuntimeError, file UNTOUCHED
body = "header\nno markers here\nfooter\n"
p = _tmpfile(body)
try:
    raised = False
    try:
        mod.atomic_replace_block(p, f"{START}\nNEW\n{END}")
    except RuntimeError:
        raised = True
    check("case2: missing marker -> RuntimeError", raised)
    check("case2: file untouched", p.read_text(encoding="utf-8") == body)
finally:
    p.unlink()

# Case 3: markers inverted (END before START) -> RuntimeError, file UNTOUCHED
body = f"header\n{END}\nbroken\n{START}\nfooter\n"
p = _tmpfile(body)
try:
    raised = False
    try:
        mod.atomic_replace_block(p, f"{START}\nNEW\n{END}")
    except RuntimeError:
        raised = True
    check("case3: inverted markers -> RuntimeError", raised)
    check("case3: file untouched", p.read_text(encoding="utf-8") == body)
finally:
    p.unlink()

print()
if all(results):
    print(f"All {len(results)} checks {PASS}")
    sys.exit(0)
print(f"{results.count(False)}/{len(results)} checks {FAIL}")
sys.exit(1)
