#!/usr/bin/env python3
"""Two side effects, one crash: keeping data consistent without duplicates (lesson AUT-204-L03). Stdlib only.

For each order event the job does two things that change the outside world:
  step 1  create a support ticket      -> the API accepts an Idempotency-Key, so retrying is safe
  step 2  send the customer a message  -> the messenger API has NO key, so a blind retry sends it twice

The step ledger (SQLite) records each step's state BEFORE and AFTER the side effect:
  new -> ticket_done -> notifying -> done
"notifying" means "we may or may not have sent it". On a rerun, an event stuck in "notifying" is RECONCILED
(look at the messenger's sent list for this event id) instead of being sent again.

Runs against the Barg Sabz mock API (barg-sabz-mock-api.py). Synthetic data.
    python partial_failure.py demo
"""
import json
import os
import sqlite3
import sys
import urllib.request

BASE = os.environ.get("MOCK_API_BASE", "http://127.0.0.1:8787")
TOKEN = os.environ.get("MOCK_API_TOKEN", "local-demo-token")
DB = os.environ.get("LEDGER_DB", "ledger.db")


class Crash(Exception):
    """Simulates the process dying (power loss, deploy, OOM) at a chosen point."""


def call(method, path, body=None, headers=None):
    h = {"Authorization": f"Bearer {TOKEN}", **(headers or {})}
    data = None
    if body is not None:
        h["Content-Type"] = "application/json"
        data = json.dumps(body, ensure_ascii=False).encode("utf-8")
    with urllib.request.urlopen(urllib.request.Request(BASE + path, data=data, method=method, headers=h), timeout=10) as r:
        return json.load(r)


def ledger():
    con = sqlite3.connect(DB)
    con.execute("CREATE TABLE IF NOT EXISTS steps (event_id TEXT PRIMARY KEY, state TEXT, ticket_id TEXT)")
    return con


def set_state(con, eid, state, ticket_id=None):
    con.execute("INSERT INTO steps VALUES (?,?,?) ON CONFLICT(event_id) DO UPDATE SET state=excluded.state, "
                "ticket_id=COALESCE(excluded.ticket_id, steps.ticket_id)", (eid, state, ticket_id))
    con.commit()


def already_sent(eid):
    """Reconcile: did the messenger already receive a message for this event?"""
    return any(f"[{eid}]" in m["text"] for m in call("GET", "/sent-messages")["data"])


def process(con, event, crash_after_send=False, reconcile=True):
    eid = event["event_id"]
    row = con.execute("SELECT state, ticket_id FROM steps WHERE event_id=?", (eid,)).fetchone()
    state, ticket = row if row else ("new", None)
    if state == "done":
        return f"{eid}: already done, skipped"
    if state == "new":
        t = call("POST", "/tickets", {"customer_ref": event["order_id"], "category": "order_shipping",
                                      "text": f"order event {eid}"}, {"Idempotency-Key": eid})
        ticket = t["id"]
        set_state(con, eid, "ticket_done", ticket)
        state = "ticket_done"
    if state == "notifying":
        if reconcile and already_sent(eid):
            set_state(con, eid, "done")
            return f"{eid}: reconciled, message was already sent; nothing resent"
        if reconcile:
            state = "ticket_done"  # not found on the messenger side: safe to send now
        else:
            state = "ticket_done"  # naive rerun: sends again without checking
    if state == "ticket_done":
        set_state(con, eid, "notifying")            # BEFORE the side effect
        call("POST", "/botDEMO/sendMessage", {"chat_id": event["chat_id"],
                                              "text": f"[{eid}] تیکت {ticket} برای سفارش {event['order_id']} ثبت شد."})
        if crash_after_send:
            raise Crash(f"{eid}: process died after sending, before recording")
        set_state(con, eid, "done")                 # AFTER the side effect
    return f"{eid}: ticket {ticket} + message sent"


def counts(eid):
    tickets = sum(1 for t in call("GET", "/tickets")["data"] if t["text"].endswith(eid))
    msgs = sum(1 for m in call("GET", "/sent-messages")["data"] if f"[{eid}]" in m["text"])
    return f"{eid}: {tickets} ticket(s), {msgs} message(s)"


def demo():
    if os.path.exists(DB):
        os.remove(DB)
    con = ledger()
    tag = os.urandom(3).hex()   # fresh ids so the demo can run again on the same mock server
    e1 = {"event_id": f"evt-ok-{tag}", "order_id": "BS-1002", "chat_id": 70001}
    e2 = {"event_id": f"evt-crash-{tag}", "order_id": "BS-1005", "chat_id": 70002}
    e3 = {"event_id": f"evt-naive-{tag}", "order_id": "BS-1006", "chat_id": 70003}
    print("== 1) normal run");                      print("  ", process(con, e1))
    print("== 2) crash after sending, before recording")
    try:
        process(con, e2, crash_after_send=True)
    except Crash as c:
        print("   CRASH:", c)
    print("   ledger state:", con.execute("SELECT state FROM steps WHERE event_id=?", (e2["event_id"],)).fetchone()[0])
    print("== 3) rerun with reconcile");            print("  ", process(con, e2))
    print("== 4) same crash, rerun WITHOUT reconcile (what a blind retry does)")
    try:
        process(con, e3, crash_after_send=True)
    except Crash as c:
        print("   CRASH:", c)
    print("  ", process(con, e3, reconcile=False))
    print("== 5) run everything again (e.g. the scheduler fired twice)")
    for e in (e1, e2, e3):
        print("  ", process(con, e))
    print("== 6) what the outside world saw")
    for e in (e1, e2, e3):
        print("  ", counts(e["event_id"]))


if __name__ == "__main__":
    if sys.argv[1:] != ["demo"]:
        sys.exit("usage: python partial_failure.py demo")
    demo()
