"""Capture real observations from two tiny, explicitly fictional source fixtures."""

import hashlib
import importlib.util
import json
from pathlib import Path


ROOT = Path(__file__).parent


def load(name):
    path = ROOT / f"batchpub_{name}.py"
    spec = importlib.util.spec_from_file_location(name, path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


def normal_cases(module):
    results = []
    for closed in (False, True):
        pending, published = ["A", "B"], []
        module.flush(pending, published, closed=closed)
        results.append({
            "case": "close_drain" if closed else "normal_flush",
            "pending": list(pending),
            "published": list(published),
            "passed": pending == [] and published == ["A", "B"],
        })
    pending, published = ["A", "B"], []
    module.flush(pending, published, closed=True)
    module.flush(pending, published, closed=True)
    results.append({
        "case": "repeat_close_flush",
        "pending": list(pending),
        "published": list(published),
        "passed": pending == [] and published == ["A", "B"],
    })
    return results


class FailOnceOnB(list):
    def __init__(self):
        super().__init__()
        self.failed = False

    def append(self, value):
        if value == "B" and not self.failed:
            self.failed = True
            raise RuntimeError("simulated sink rejection on B")
        super().append(value)


def failure_probe(module):
    pending, published = ["A", "B"], FailOnceOnB()
    caught = None
    try:
        module.flush(pending, published, closed=True)
    except RuntimeError as error:
        caught = str(error)
    after_failure = {"pending": list(pending), "published": list(published), "exception": caught}
    module.flush(pending, published, closed=True)
    return {
        "case": "partial_publish_then_retry",
        "after_failure": after_failure,
        "after_retry": {"pending": list(pending), "published": list(published)},
        "duplicate_free": list(published) == ["A", "B"],
    }


if __name__ == "__main__":
    before, after = load("before"), load("after")
    print(json.dumps({
        "scope": "Executed locally against fictional Python fixtures; no devices or real product source.",
        "files": {p.name: hashlib.sha256(p.read_bytes()).hexdigest() for p in sorted(ROOT.glob("*.py"))},
        "before": normal_cases(before),
        "after": normal_cases(after),
        "after_failure_probe": failure_probe(after),
    }, indent=2, ensure_ascii=False))
