"""Synthetic free sample: duplicate callback after simulated response loss."""
import argparse
import json
import os
from pathlib import Path
import re
import sqlite3
import sys

FIXTURE = {"scenario": "duplicate_callback_after_simulated_lost_response",
           "synthetic": True, "event_id": "demo-event-001", "order_id": "demo-order-001"}
BLOCKED_EVENTS = ("socket.__new__", "socket.getaddrinfo", "subprocess.Popen",
                  "os.system", "os.exec", "os.posix_spawn", "os.fork")
TEXT = ("BROKEN: caught expected invariant failure (events=1, entitlements=2).\n"
        "CORRECTED: invariant passed (events=1, entitlements=1; recovered same receipt=True).\n"
        "PASS: simulated response-loss replay behaved as expected.\n")

def install_audit_guard():
    # Supplemental CPython audit guard, not a sandbox for untrusted code.
    def guard(event, _arguments):
        if event.startswith(("socket.", "subprocess.", "pty.")) or event in (
                "os.system", "os.exec", "os.posix_spawn", "os.spawn", "os.fork",
                "os.forkpty", "os.kill", "os.killpg", "os.startfile"):
            raise RuntimeError("Network and process actions are disabled in this sample")
    sys.addaudithook(guard)

def refuse_credentials():
    pattern = r"TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|AUTH|PRIVATE.?KEY|RECOVERY.?KEY|API.?KEY|ACCESS.?KEY|DATABASE.?URL|MNEMONIC|SEED|KEYSTORE|(^|_)DSN($|_)"
    if any(re.search(pattern, name, re.I) for name in os.environ):
        raise ValueError("Refused credential-like environment names; use a clean environment")

def load_fixture():
    fixture = json.loads(Path(__file__).with_name("fixture.json").read_text(encoding="utf-8"))
    if fixture != FIXTURE or fixture.get("synthetic") is not True:
        raise ValueError("Only the bundled, fixed synthetic fixture is accepted")
    return fixture

def check_path(path):
    for entry in [*path.parents][::-1] + [path]:
        if entry.is_symlink():
            raise ValueError("Refused a symlink in the output path or its ancestors")

def new_output(raw):
    if ".." in Path(raw).parts:
        raise ValueError("Parent traversal is not accepted")
    path = Path(os.path.abspath(raw))  # Do not resolve away symlink evidence.
    check_path(path)
    if os.path.lexists(path):
        raise ValueError("Output must be a new directory; existing paths are never overwritten")
    if not path.parent.is_dir():
        raise ValueError("Output parent must already exist")
    path.mkdir(mode=0o700)
    return path

def create_schema(db, corrected):
    unique = " UNIQUE" if corrected else ""
    with db:
        db.execute("CREATE TABLE events (event_id TEXT PRIMARY KEY, order_id TEXT NOT NULL)")
        db.execute("CREATE TABLE entitlements (receipt_id TEXT PRIMARY KEY, order_id TEXT NOT NULL" + unique + ")")

def callback(db, fixture, corrected):
    with db:  # Event acceptance and entitlement creation commit together.
        stored = db.execute("SELECT receipt_id FROM entitlements WHERE order_id = ?",
                            (fixture["order_id"],)).fetchone()
        if corrected and stored:
            return stored[0]
        db.execute("INSERT OR IGNORE INTO events VALUES (?, ?)",
                   (fixture["event_id"], fixture["order_id"]))
        count = db.execute("SELECT COUNT(*) FROM entitlements").fetchone()[0]
        receipt = "demo-receipt-%03d" % (count + 1)
        db.execute("INSERT INTO entitlements VALUES (?, ?)", (receipt, fixture["order_id"]))
    return receipt

def invariant(events, entitlements):
    return events == 1 and entitlements == 1

class SimulatedResponseLoss(Exception):
    pass

def run_model(path, fixture, corrected):
    check_path(path)
    with path.open("xb"):  # Exclusive creation in the newly created output directory.
        pass
    db = sqlite3.connect(path)
    try:
        create_schema(db, corrected)
        first = callback(db, fixture, corrected)  # Observer knows this persisted receipt.
    finally:
        db.close()
    try:
        raise SimulatedResponseLoss()  # No real response or network operation exists.
    except SimulatedResponseLoss:
        check_path(path)
        db = sqlite3.connect(path)  # A fresh connection proves state survives reopening.
    try:
        replay = callback(db, fixture, corrected)
        events = db.execute("SELECT COUNT(*) FROM events").fetchone()[0]
        entitlements = db.execute("SELECT COUNT(*) FROM entitlements").fetchone()[0]
    finally:
        db.close()
    return {"accepted_events": events, "entitlements": entitlements,
            "invariant_passed": invariant(events, entitlements), "first_receipt": first,
            "replay_receipt": replay, "same_receipt": first == replay}

def main(argv=None):
    parser = argparse.ArgumentParser(description=__doc__)
    options = parser.add_mutually_exclusive_group(required=True)
    options.add_argument("--output", metavar="NEWDIR")
    options.add_argument("--self-test", action="store_true", help="Probe guards without real I/O")
    args = parser.parse_args(argv)
    try:
        refuse_credentials()
        install_audit_guard()
        if sys.platform not in ("linux", "darwin"):
            raise ValueError("This sample supports Linux/macOS paths; Windows is not supported")
        if args.self_test:
            for event in BLOCKED_EVENTS:
                try:
                    sys.audit(event)
                except RuntimeError:
                    continue
                raise RuntimeError("An audit probe was not blocked")
            print("PASS: 7 network/process audit probes blocked; no real I/O attempted.")
            return 0
        fixture = load_fixture()
        output = new_output(args.output)
        report = {"scenario": fixture["scenario"], "synthetic": True,
                  "response_loss": "simulated_after_commit"}
        for name, corrected in (("broken", False), ("corrected", True)):
            report[name] = run_model(output / (name + ".sqlite3"), fixture, corrected)
        broken, fixed = report["broken"], report["corrected"]
        if ((broken["accepted_events"], broken["entitlements"]) != (1, 2)
                or broken["invariant_passed"] or broken["same_receipt"]
                or not (fixed["invariant_passed"] and fixed["same_receipt"])):
            raise RuntimeError("The expected broken/corrected comparison did not hold")
        for name, content in (("result.json", json.dumps(report, indent=2, sort_keys=True) + "\n"),
                              ("result.txt", TEXT)):
            path = output / name
            check_path(path)
            with path.open("x", encoding="utf-8") as stream:
                stream.write(content)
        print(TEXT, end="")
        return 0
    except (ValueError, OSError, RuntimeError, sqlite3.Error) as error:
        print("ERROR: " + str(error), file=sys.stderr)
        return 2


if __name__ == "__main__":
    sys.exit(main())
