#!/usr/bin/env python3
"""Fixed authored SQLite inbox/outbox-intent exercise; no HTTP or dispatcher."""

import contextlib
import json
import os
from pathlib import Path
import sqlite3
import subprocess
import sys
import tempfile


BODY_FIELDS = {"payload_version", "event_id", "event_type", "resource_id", "delta_units"}
ENVELOPE_FIELDS = {"source", "account_id", "delivery_id", "body"}
VARIANTS = ("event", "attempt", "resource")
EXPECTED_INTENTS = [
    {"intent_version": 1, "intent_type": "apply_inventory_delta", "source": "source_alpha", "account_id": "acct_one", "event_id": "evt_A", "resource_id": "item_demo_001", "delta_units": 3},
    {"intent_version": 1, "intent_type": "apply_inventory_delta", "source": "source_alpha", "account_id": "acct_one", "event_id": "evt_B", "resource_id": "item_demo_001", "delta_units": 2},
    {"intent_version": 1, "intent_type": "apply_inventory_delta", "source": "source_alpha", "account_id": "acct_two", "event_id": "evt_A", "resource_id": "item_demo_001", "delta_units": 3},
    {"intent_version": 1, "intent_type": "apply_inventory_delta", "source": "source_beta", "account_id": "acct_one", "event_id": "evt_A", "resource_id": "item_demo_001", "delta_units": 3},
]
EXPECTED_PROJECTION = [
    ["source_alpha", "acct_one", "item_demo_001", 5],
    ["source_alpha", "acct_two", "item_demo_001", 3],
    ["source_beta", "acct_one", "item_demo_001", 3],
]


def canonical(value):
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True)


def body(event_id="evt_A", delta=3):
    return {"payload_version": 1, "event_id": event_id, "event_type": "inventory.adjusted", "resource_id": "item_demo_001", "delta_units": delta}


def delivery(delivery_id, payload=None, source="source_alpha", account="acct_one"):
    return {"source": source, "account_id": account, "delivery_id": delivery_id, "body": json.dumps(body() if payload is None else payload)}


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError("ambiguous duplicate JSON property")
        result[key] = value
    return result


def parse(envelope):
    if not isinstance(envelope, dict) or set(envelope) != ENVELOPE_FIELDS:
        raise ValueError("invalid envelope fields")
    for name in ("source", "account_id", "delivery_id", "body"):
        if not isinstance(envelope[name], str) or not envelope[name].strip():
            raise ValueError("envelope strings must be nonempty")
    payload = json.loads(envelope["body"], object_pairs_hook=unique_object)
    if not isinstance(payload, dict) or set(payload) != BODY_FIELDS:
        raise ValueError("invalid semantic body fields")
    if type(payload["payload_version"]) is not int or payload["payload_version"] != 1:
        raise ValueError("unsupported payload version")
    if payload["event_type"] != "inventory.adjusted":
        raise ValueError("unsupported event type")
    for name in ("event_id", "resource_id"):
        if not isinstance(payload[name], str) or not payload[name].strip():
            raise ValueError("event and resource IDs must be nonempty strings")
    delta = payload["delta_units"]
    if type(delta) is not int or not -(2 ** 63) <= delta < 2 ** 63:
        raise ValueError("delta must be a signed SQLite integer, excluding bool")
    return payload


def connect(path):
    connection = sqlite3.connect(path, isolation_level=None)
    connection.execute("PRAGMA journal_mode=DELETE")
    connection.execute("PRAGMA synchronous=FULL")
    connection.execute("PRAGMA foreign_keys=ON")
    return connection


def initialize(path):
    with contextlib.closing(connect(path)) as connection:
        connection.executescript("""
            CREATE TABLE inbox (
                dedupe_key TEXT PRIMARY KEY NOT NULL,
                semantic_json TEXT NOT NULL
            );
            CREATE TABLE outbox (
                intent_key TEXT PRIMARY KEY NOT NULL REFERENCES inbox(dedupe_key),
                intent_json TEXT NOT NULL
            );
        """)
        return {name: connection.execute("PRAGMA " + name).fetchone()[0]
                for name in ("journal_mode", "synchronous", "foreign_keys")}


def consume(connection, envelope, variant="event", after_inbox=None, after_commit=None):
    payload = parse(envelope)
    if variant not in VARIANTS:
        raise ValueError("unknown exercise variant")
    identity = {"event": payload["event_id"], "attempt": envelope["delivery_id"], "resource": payload["resource_id"]}[variant]
    key = canonical([envelope["source"], envelope["account_id"], identity])
    semantic = canonical(payload)  # Includes every accepted body field, no attempt metadata.
    intent = {"intent_version": 1, "intent_type": "apply_inventory_delta", "source": envelope["source"], "account_id": envelope["account_id"], "event_id": payload["event_id"], "resource_id": payload["resource_id"], "delta_units": payload["delta_units"]}
    try:
        connection.execute("BEGIN IMMEDIATE")
        previous = connection.execute("SELECT semantic_json FROM inbox WHERE dedupe_key=?", (key,)).fetchone()
        if previous is not None:
            connection.execute("ROLLBACK")
            return "duplicate" if previous[0] == semantic else "conflict"
        connection.execute("INSERT INTO inbox VALUES (?, ?)", (key, semantic))
        if after_inbox is not None:
            after_inbox()
        connection.execute("INSERT INTO outbox VALUES (?, ?)", (key, canonical(intent)))
        connection.execute("COMMIT")
        if after_commit is not None:
            after_commit()
        return "stored"  # Local acknowledgement only after COMMIT returned.
    except BaseException:
        if connection.in_transaction:
            connection.execute("ROLLBACK")
        raise


def snapshot(path):
    with contextlib.closing(connect(path)) as connection:
        inbox = connection.execute("SELECT dedupe_key, semantic_json FROM inbox ORDER BY dedupe_key").fetchall()
        intents = [json.loads(row[0]) for row in connection.execute("SELECT intent_json FROM outbox")]
        unpaired = connection.execute("SELECT COUNT(*) FROM inbox i LEFT JOIN outbox o ON i.dedupe_key=o.intent_key WHERE o.intent_key IS NULL").fetchone()[0]
        foreign_key_errors = connection.execute("PRAGMA foreign_key_check").fetchall()
    return {"inbox": inbox, "intents": sorted(intents, key=canonical), "unpaired": unpaired, "foreign_key_errors": foreign_key_errors}


def project(intents):
    totals = {}
    for intent in intents:
        scope = (intent["source"], intent["account_id"], intent["resource_id"])
        totals[scope] = totals.get(scope, 0) + intent["delta_units"]
    return [list(scope) + [total] for scope, total in sorted(totals.items())]


def oracle(state, expected_intents, expected_projection):
    # Expected records are declared independently, never derived from a variant key.
    issues = []
    if state["intents"] != sorted(expected_intents, key=canonical):
        issues.append("full intent records differ")
    if project(state["intents"]) != expected_projection:
        issues.append("projected units differ")
    if len(state["inbox"]) != len(expected_intents) or state["unpaired"] or state["foreign_key_errors"]:
        issues.append("inbox/outbox correspondence differs")
    return issues


def require(condition, message):
    if not condition:
        raise AssertionError(message)


def fixtures():
    reordered = delivery("attempt_A2")
    reordered["body"] = ' { "delta_units": 3, "resource_id": "item_demo_001", "event_type": "inventory.adjusted", "event_id": "evt_A", "payload_version": 1 } '
    return [delivery("attempt_A1"), reordered, delivery("attempt_B1", body("evt_B", 2)),
            delivery("attempt_other_account", account="acct_two"), delivery("attempt_other_source", source="source_beta")]


def check_variants(root):
    for variant, label in (("event", "correct key"), ("attempt", "rejected attempt-ID key"), ("resource", "rejected resource-ID key")):
        path = root / (variant + ".sqlite3")
        initialize(path)
        with contextlib.closing(connect(path)) as connection:
            statuses = [consume(connection, item, variant) for item in fixtures()]
        state = snapshot(path)  # Reopen; inspect persistent records, not returned counts.
        issues = oracle(state, EXPECTED_INTENTS, EXPECTED_PROJECTION)
        if statuses != ["stored", "duplicate", "stored", "stored", "stored"]:
            issues.append("handling results differ")
        require(not issues if variant == "event" else bool(issues), variant + " did not meet its expected oracle disposition")
        print("PASS " + label + ": projection=" + canonical(project(state["intents"])) + ("; " + ", ".join(issues) if issues else ""))


def check_conflict(root):
    path = root / "conflict.sqlite3"
    initialize(path)
    with contextlib.closing(connect(path)) as connection:
        statuses = [consume(connection, delivery("first")), consume(connection, delivery("changed", body(delta=99))), consume(connection, fixtures()[1])]
    state = snapshot(path)
    require(statuses == ["stored", "conflict", "duplicate"], "semantic conflict/reordered-body handling differs")
    require(not oracle(state, EXPECTED_INTENTS[:1], [["source_alpha", "acct_one", "item_demo_001", 3]]), "conflict altered the accepted intent")
    require(json.loads(state["inbox"][0][1]) == body(), "conflict replaced the accepted semantic body")
    print("PASS semantic conflict / reordered JSON: original intent retained; changed intent refused")


def check_schema():
    samples = [delivery("bool", body(delta=True)), delivery("extra", dict(body(), extra="unrecognized")),
               delivery("version", dict(body(), payload_version=True)), dict(delivery("scope"), account_id="")]
    for item in samples:
        try:
            parse(item)
        except ValueError:
            continue
        raise AssertionError("closed envelope/body negative control was accepted")
    print("PASS closed envelope/body contract: bool, unknown field, invalid version and empty scope refused")


def child_main(path, point, expected_parent):
    # Internal mode is only for the driver's own child and temporary database.
    marker = path.parent / ".exercise-owner"
    require(os.getppid() == expected_parent and marker.read_text() == str(expected_parent), "unowned child invocation")
    require(path.parent.name.startswith("webhook-idempotency-") and path.name in ("before.sqlite3", "after.sqlite3"), "unexpected child database")
    require(point in ("before", "after") and path.exists(), "invalid failpoint")
    with contextlib.closing(connect(path)) as connection:
        consume(connection, delivery("child_attempt"),
                after_inbox=(lambda: os._exit(71)) if point == "before" else None,
                after_commit=(lambda: os._exit(72)) if point == "after" else None)
    raise AssertionError("owned child missed its failpoint")


def check_restart(root, point):
    path = root / (point + ".sqlite3")
    initialize(path)
    child = subprocess.run([sys.executable, str(Path(__file__).resolve()), "--owned-child", str(path), point, str(os.getpid())], capture_output=True, text=True, timeout=10)
    require(child.returncode == (71 if point == "before" else 72), "child failpoint exit differed: " + repr((child.returncode, child.stdout, child.stderr)))
    before_retry = snapshot(path)
    expected_one = EXPECTED_INTENTS[:1]
    projection_one = [["source_alpha", "acct_one", "item_demo_001", 3]]
    if point == "before":
        require(not before_retry["inbox"] and not before_retry["intents"], "partial acceptance survived before commit")
    else:
        require(not oracle(before_retry, expected_one, projection_one), "successful commit was not visible after reopen")
    with contextlib.closing(connect(path)) as connection:
        retry = consume(connection, delivery("retry_after_restart"))
        duplicate = consume(connection, fixtures()[1])
    require(retry == ("stored" if point == "before" else "duplicate") and duplicate == "duplicate", "restart retry handling differs")
    require(not oracle(snapshot(path), expected_one, projection_one), "restart changed the single intended effect")
    label = "pre-commit restart" if point == "before" else "post-commit / pre-ack restart"
    print("PASS " + label + ": child_exit=" + str(child.returncode) + "; retry=" + retry + "; one durable intent")


def main():
    if len(sys.argv) == 5 and sys.argv[1] == "--owned-child":
        child_main(Path(sys.argv[2]), sys.argv[3], int(sys.argv[4]))
        return
    require(len(sys.argv) == 1, "Usage: python3 exercise.py (fixed authored exercise only)")
    print("AUTHORED LOCAL EXERCISE: durable inbox + outbox INTENT; no external dispatch")
    with tempfile.TemporaryDirectory(prefix="webhook-idempotency-") as directory:
        root = Path(directory)
        (root / ".exercise-owner").write_text(str(os.getpid()))
        settings = initialize(root / "settings.sqlite3")
        require(settings == {"journal_mode": "delete", "synchronous": 2, "foreign_keys": 1}, "effective SQLite settings differ")
        print("Environment: Python=" + sys.version.split()[0] + "; SQLite=" + sqlite3.sqlite_version + "; settings=" + canonical(settings))
        check_variants(root)
        check_conflict(root)
        check_schema()
        check_restart(root, "before")
        check_restart(root, "after")
    print("PASS local inbox/outbox-intent exercise; temporary databases cleaned")


if __name__ == "__main__":
    try:
        main()
    except Exception as error:
        print("FAIL " + type(error).__name__ + ": " + str(error), file=sys.stderr)
        sys.exit(1)
