"""Educational local order journal. No broker, credentials, network or SDK.

Demonstrates durable intent identity and conservative retry handling in SQLite.
Permission creation/revocation and outcome recording require a trusted caller.
There is no authentication, portfolio risk engine or live execution adapter here.
"""
from contextlib import contextmanager
from dataclasses import dataclass, replace
import json
from pathlib import Path
import re
import sqlite3
from tempfile import TemporaryDirectory


def identifier(value):
    return isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_.:-]{1,96}", value) is not None


def positive_int(value):
    return type(value) is int and 0 < value <= 10**12


@dataclass(frozen=True)
class Intent:
    account: str
    agent: str
    symbol: str
    quantity: int
    limit_cents: int


class Journal:
    def __init__(self, path):
        self.db = sqlite3.connect(path, isolation_level=None, timeout=10)
        self.db.execute("PRAGMA synchronous=FULL")
        self.db.executescript("""
            CREATE TABLE IF NOT EXISTS permissions (
                id TEXT PRIMARY KEY, account TEXT NOT NULL, agent TEXT NOT NULL,
                expires_at INTEGER NOT NULL, revoked INTEGER NOT NULL DEFAULT 0);
            CREATE TABLE IF NOT EXISTS attempts (
                id TEXT PRIMARY KEY, permission_id TEXT NOT NULL,
                payload TEXT NOT NULL, state TEXT NOT NULL);
            CREATE TABLE IF NOT EXISTS audit (
                seq INTEGER PRIMARY KEY, operation_id TEXT NOT NULL, event TEXT NOT NULL);
            CREATE TRIGGER IF NOT EXISTS audit_no_update BEFORE UPDATE ON audit
                BEGIN SELECT RAISE(ABORT, 'audit is append-only'); END;
            CREATE TRIGGER IF NOT EXISTS audit_no_delete BEFORE DELETE ON audit
                BEGIN SELECT RAISE(ABORT, 'audit is append-only'); END;
        """)

    def close(self):
        self.db.close()

    @contextmanager
    def transaction(self):
        # Serializes competing local writers, including revoke and dispatch claims.
        self.db.execute("BEGIN IMMEDIATE")
        try:
            yield
            self.db.execute("COMMIT")
        except BaseException:
            self.db.execute("ROLLBACK")
            raise

    def event(self, key, event):
        self.db.execute("INSERT INTO audit(operation_id,event) VALUES (?,?)", (key, event))

    def create_permission(self, permission_id, account, agent, expires_at):
        if not all(map(identifier, (permission_id, account, agent))) or not positive_int(expires_at):
            raise ValueError("invalid permission")
        with self.transaction():
            # Never upsert: a revoked permission identifier cannot be resurrected.
            self.db.execute("INSERT INTO permissions VALUES (?,?,?,?,0)",
                            (permission_id, account, agent, expires_at))
            self.event(permission_id, "permission_created")

    def revoke(self, permission_id):
        with self.transaction():
            changed = self.db.execute("UPDATE permissions SET revoked=1 WHERE id=?",
                                      (permission_id,)).rowcount
            if changed != 1:
                raise ValueError("unknown permission")
            self.event(permission_id, "permission_revoked")

    def permission_error(self, permission_id, intent, now):
        row = self.db.execute("SELECT account,agent,expires_at,revoked FROM permissions WHERE id=?",
                              (permission_id,)).fetchone()
        if row is None:
            return "permission_unknown"
        account, agent, expires_at, revoked = row
        if (account, agent) != (intent.account, intent.agent):
            return "identity_mismatch"
        if revoked:
            return "permission_revoked"
        if now >= expires_at:
            return "permission_expired"
        return None

    def reserve(self, key, permission_id, intent, *, now):
        if (not isinstance(intent, Intent) or not all(map(identifier,
                (key, permission_id, intent.account, intent.agent, intent.symbol)))
                or not positive_int(intent.quantity) or not positive_int(intent.limit_cents)
                or type(now) is not int or not 0 <= now <= 10**12):
            return "invalid_intent"
        payload = json.dumps([permission_id, intent.account, intent.agent, intent.symbol,
                              intent.quantity, intent.limit_cents], separators=(",", ":"))
        with self.transaction():
            existing = self.db.execute("SELECT payload,state FROM attempts WHERE id=?", (key,)).fetchone()
            if existing:
                if existing[0] != payload:
                    return "idempotency_conflict"
                # A repeat is an observation, never another dispatch permission.
                return "reconcile_required" if existing[1] in ("RESERVED", "UNKNOWN") else "already_recorded"
            error = self.permission_error(permission_id, intent, now)
            if error:
                return error
            self.db.execute("INSERT INTO attempts VALUES (?,?,?,?)", (key, permission_id, payload, "RESERVED"))
            self.event(key, "intent_reserved")
            return "reserved_for_simulation"

    def claim_dispatch(self, key, *, now):
        if not identifier(key) or type(now) is not int or not 0 <= now <= 10**12:
            return "invalid_intent"
        with self.transaction():
            row = self.db.execute("SELECT permission_id,payload,state FROM attempts WHERE id=?", (key,)).fetchone()
            if row is None:
                return "intent_unknown"
            permission_id, payload, state = row
            if state != "RESERVED":
                return "reconcile_required" if state == "UNKNOWN" else "already_recorded"
            fields = json.loads(payload)
            error = self.permission_error(permission_id, Intent(*fields[1:]), now)
            if error:
                self.db.execute("UPDATE attempts SET state='BLOCKED' WHERE id=?", (key,))
                self.event(key, error)
                return error
            # Persist uncertainty BEFORE a hypothetical external call. A crash
            # here can hold an unsent order, but cannot grant a blind second send.
            self.db.execute("UPDATE attempts SET state='UNKNOWN' WHERE id=?", (key,))
            self.event(key, "dispatch_claimed_for_simulation")
            return "dispatch_once_for_simulation"

    def record_outcome(self, key, outcome):
        if outcome not in ("ACKNOWLEDGED", "FILLED", "REJECTED"):
            raise ValueError("invalid outcome")
        with self.transaction():
            row = self.db.execute("SELECT state FROM attempts WHERE id=?", (key,)).fetchone()
            if row is None or (row[0] not in ("UNKNOWN", "ACKNOWLEDGED") and row[0] != outcome):
                raise ValueError("invalid outcome transition")
            if row[0] != outcome:
                self.db.execute("UPDATE attempts SET state=? WHERE id=?", (outcome, key))
                self.event(key, outcome)


def scenarios():
    rows = []
    def observed(name, value):
        rows.append({"scenario": name, "result": value})
    with TemporaryDirectory(prefix="galore-journal-") as directory:
        path = str(Path(directory) / "paper.sqlite")
        j = Journal(path)
        intent = Intent("paper-account", "example-agent", "EXAMPLE", 1, 10000)
        j.create_permission("p1", intent.account, intent.agent, 100)
        observed("first_intent", j.reserve("order-1", "p1", intent, now=10))
        observed("first_dispatch_claim", j.claim_dispatch("order-1", now=11))
        observed("retry_after_unknown_outcome", j.reserve("order-1", "p1", intent, now=12))
        observed("second_dispatch_claim", j.claim_dispatch("order-1", now=12))
        observed("same_key_changed_order", j.reserve("order-1", "p1", replace(intent, quantity=2), now=12))
        j.close()
        j = Journal(path)
        observed("retry_after_restart", j.reserve("order-1", "p1", intent, now=13))
        j.record_outcome("order-1", "ACKNOWLEDGED")
        observed("acknowledged_is_not_filled", j.db.execute("SELECT state FROM attempts WHERE id='order-1'").fetchone()[0])
        j.record_outcome("order-1", "FILLED")
        observed("retry_after_fill", j.reserve("order-1", "p1", intent, now=14))
        observed("wrong_agent", j.reserve("order-2", "p1", replace(intent, agent="other"), now=14))
        observed("invalid_quantity", j.reserve("order-2", "p1", replace(intent, quantity=True), now=14))
        j.revoke("p1")
        observed("new_order_after_revoke", j.reserve("order-2", "p1", intent, now=14))
        j.create_permission("p2", intent.account, intent.agent, 20)
        j.reserve("order-3", "p2", intent, now=19)
        j.revoke("p2")
        observed("revoke_between_reserve_and_dispatch", j.claim_dispatch("order-3", now=19))
        j.create_permission("p3", intent.account, intent.agent, 20)
        observed("expiry_boundary", j.reserve("order-4", "p3", intent, now=20))
        j.close()
    return {"example": "local SQLite retry journal", "broker_requests": 0,
            "dispatch_claims_for_simulation": 1, "results": rows}


if __name__ == "__main__":
    print(json.dumps(scenarios(), indent=2))
