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58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
"""Deterministic local business store for the Backcountry offline clone.

Persistence goes through the generated ``site_backend_integration`` seam so the
site keeps its own bound SQLite database, session cookie and mail outbox. This
module owns only the site's business tables: carts, cart lines, wish lists,
orders and addresses. Authentication, sessions and mail stay with
``LocalAuthStore``; nothing here reimplements them.
"""

from __future__ import annotations

import json
import sqlite3
import threading
from dataclasses import dataclass
from typing import Any

from backend.site_backend_integration import open_site_services

SCHEMA = """
CREATE TABLE IF NOT EXISTS clone_cart (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  actor TEXT NOT NULL UNIQUE,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE TABLE IF NOT EXISTS clone_cart_line (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  cart_id INTEGER NOT NULL REFERENCES clone_cart(id) ON DELETE CASCADE,
  sku_id TEXT NOT NULL,
  product_slug TEXT NOT NULL,
  color TEXT,
  size TEXT,
  quantity INTEGER NOT NULL CHECK (quantity > 0),
  unit_price REAL NOT NULL,
  list_price REAL NOT NULL,
  added_at TEXT NOT NULL DEFAULT (datetime('now')),
  UNIQUE (cart_id, sku_id)
);
CREATE TABLE IF NOT EXISTS clone_wishlist (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  actor TEXT NOT NULL,
  product_slug TEXT NOT NULL,
  color TEXT,
  added_at TEXT NOT NULL DEFAULT (datetime('now')),
  UNIQUE (actor, product_slug, color)
);
CREATE TABLE IF NOT EXISTS clone_order (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  order_number TEXT NOT NULL UNIQUE,
  actor TEXT NOT NULL,
  placed_on TEXT NOT NULL,
  status TEXT NOT NULL,
  ship_to TEXT NOT NULL,
  subtotal REAL NOT NULL,
  shipping REAL NOT NULL,
  tax REAL NOT NULL,
  total REAL NOT NULL,
  lines TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS clone_address (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  actor TEXT NOT NULL,
  label TEXT NOT NULL,
  recipient TEXT NOT NULL,
  line1 TEXT NOT NULL,
  line2 TEXT,
  city TEXT NOT NULL,
  region TEXT NOT NULL,
  postal_code TEXT NOT NULL,
  country TEXT NOT NULL,
  is_default INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS clone_outbox (
  id INTEGER PRIMARY KEY AUTOINCREMENT,
  channel TEXT NOT NULL,
  recipient TEXT NOT NULL,
  purpose TEXT NOT NULL,
  created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
"""

# The one synthetic member the clone ships with. No source credential is used
# or stored; this account exists only inside the local database.
MEMBER = {
    "email": "gearhead.demo@backcountry.offline.invalid",
    "password": "GearheadDemo!2026",
    "first_name": "Alex",
    "last_name": "Rivera",
    "tier": "Summit Club Member",
}

SEED_ADDRESSES = [
    {"label": "Home", "recipient": "Alex Rivera", "line1": "1284 Wasatch Loop", "line2": "Apt 4",
     "city": "Salt Lake City", "region": "UT", "postal_code": "84109", "country": "United States",
     "is_default": 1},
    {"label": "Work", "recipient": "Alex Rivera", "line1": "2607 South 3200 West", "line2": None,
     "city": "West Valley City", "region": "UT", "postal_code": "84119", "country": "United States",
     "is_default": 0},
]

SEED_ORDERS = [
    {"order_number": "BC-4820117", "placed_on": "2026-07-18", "status": "Delivered",
     "ship_to": "Home", "shipping": 0.0,
     "lines": [{"product_slug": "/patagonia-black-hole-40l-duffel-bag", "sku_id": "PATZAKX-BERFIG-ONESIZ",
                "color": "Berry Fig", "size": "One Size", "quantity": 1, "unit_price": 165.0}]},
    {"order_number": "BC-4791560", "placed_on": "2026-06-02", "status": "Delivered",
     "ship_to": "Home", "shipping": 0.0,
     "lines": [{"product_slug": "/osprey-packs-daylite-13l-backpack", "sku_id": "OSPZ19S-BLA-ONESIZ",
                "color": "Black", "size": "One Size", "quantity": 2, "unit_price": 52.50},
               {"product_slug": "/patagonia-black-hole-3l-cube", "sku_id": "PATZAKW-BLABLA-ONESIZ",
                "color": "Black/Black", "size": "One Size", "quantity": 1, "unit_price": 45.0}]},
    {"order_number": "BC-4756903", "placed_on": "2026-04-11", "status": "Cancelled",
     "ship_to": "Work", "shipping": 6.95,
     "lines": [{"product_slug": "/cotopaxi-allpa-del-dia-35l-travel-pack", "sku_id": "CTXB0IE-DELDIA-ONESIZ",
                "color": "Del Dia", "size": "One Size", "quantity": 1, "unit_price": 230.0}]},
]

TAX_RATE = 0.0725
FREE_SHIPPING_THRESHOLD = 69.0
STANDARD_SHIPPING = 6.95

_lock = threading.Lock()


@dataclass
class Services:
    backend: Any
    auth: Any


_services: Services | None = None


def services() -> Services:
    global _services
    if _services is None:
        backend, auth = open_site_services()
        _services = Services(backend=backend, auth=auth)
        _bootstrap(_services)
    return _services


def _connect() -> sqlite3.Connection:
    conn = services().auth.connect()
    conn.row_factory = sqlite3.Row
    return conn


def _bootstrap(svc: Services) -> None:
    svc.auth.ensure_schema()
    conn = svc.auth.connect()
    try:
        conn.executescript(SCHEMA)
        conn.commit()
    finally:
        conn.close()
    if not svc.auth.account_exists(MEMBER["email"]):
        svc.auth.seed_account(
            subject_id="backcountry-member-demo",
            email=MEMBER["email"],
            display_name=f'{MEMBER["first_name"]} {MEMBER["last_name"]}',
            password=MEMBER["password"],
        )
    seed_member_data()


def seed_member_data() -> None:
    """Seed the member's deterministic fixture rows.

    Idempotent by row identity, not by actor: `clone_order.order_number` is
    globally unique, so guarding on "this actor has no orders yet" would crash
    against a row left by an earlier fixture identity.

    Every statement is a true no-op once the fixture rows are already correct.
    An `INSERT ... ON CONFLICT DO UPDATE` would not be: SQLite allocates the
    AUTOINCREMENT rowid before it detects the conflict, so `sqlite_sequence`
    advanced on every boot and consecutive restarts left different durable
    state. Repair first, then insert only what is genuinely absent.
    """
    actor = MEMBER["email"]
    conn = _connect()
    try:
        for a in SEED_ADDRESSES:
            conn.execute(
                "INSERT INTO clone_address (actor,label,recipient,line1,line2,city,region,"
                "postal_code,country,is_default) SELECT ?,?,?,?,?,?,?,?,?,? WHERE NOT EXISTS "
                "(SELECT 1 FROM clone_address WHERE actor = ? AND label = ?)",
                (actor, a["label"], a["recipient"], a["line1"], a["line2"], a["city"],
                 a["region"], a["postal_code"], a["country"], a["is_default"],
                 actor, a["label"]))
        for o in SEED_ORDERS:
            subtotal = round(sum(x["unit_price"] * x["quantity"] for x in o["lines"]), 2)
            tax = round(subtotal * TAX_RATE, 2)
            total = round(subtotal + o["shipping"] + tax, 2)
            conn.execute(
                "UPDATE clone_order SET actor = ?, placed_on = ?, status = ?, "
                "ship_to = ?, subtotal = ?, shipping = ?, tax = ?, total = ?, lines = ? "
                "WHERE order_number = ?",
                (actor, o["placed_on"], o["status"], o["ship_to"], subtotal,
                 o["shipping"], tax, total, json.dumps(o["lines"]), o["order_number"]))
            conn.execute(
                "INSERT INTO clone_order (order_number,actor,placed_on,status,ship_to,"
                "subtotal,shipping,tax,total,lines) SELECT ?,?,?,?,?,?,?,?,?,? "
                "WHERE NOT EXISTS (SELECT 1 FROM clone_order WHERE order_number = ?)",
                (o["order_number"], actor, o["placed_on"], o["status"], o["ship_to"],
                 subtotal, o["shipping"], tax, total, json.dumps(o["lines"]),
                 o["order_number"]))
        conn.commit()
    finally:
        conn.close()


# --------------------------------------------------------------------------
# cart
# --------------------------------------------------------------------------

def _cart_id(conn: sqlite3.Connection, actor: str) -> int:
    row = conn.execute("SELECT id FROM clone_cart WHERE actor = ?", (actor,)).fetchone()
    if row:
        return int(row["id"])
    cur = conn.execute("INSERT INTO clone_cart (actor) VALUES (?)", (actor,))
    return int(cur.lastrowid)


def cart_lines(actor: str) -> list[dict[str, Any]]:
    conn = _connect()
    try:
        rows = conn.execute(
            "SELECT l.* FROM clone_cart_line l JOIN clone_cart c ON c.id = l.cart_id"
            " WHERE c.actor = ? ORDER BY l.added_at, l.id", (actor,)).fetchall()
        return [dict(r) for r in rows]
    finally:
        conn.close()


def cart_count(actor: str) -> int:
    conn = _connect()
    try:
        row = conn.execute(
            "SELECT COALESCE(SUM(l.quantity), 0) AS n FROM clone_cart_line l"
            " JOIN clone_cart c ON c.id = l.cart_id WHERE c.actor = ?", (actor,)).fetchone()
        return int(row["n"])
    finally:
        conn.close()


def add_to_cart(actor: str, *, sku_id: str, product_slug: str, color: str | None,
                size: str | None, unit_price: float, list_price: float, quantity: int = 1) -> None:
    if quantity < 1:
        raise ValueError("quantity must be positive")
    with _lock:
        conn = _connect()
        try:
            cart_id = _cart_id(conn, actor)
            # Idempotent per SKU: re-adding the same variant increments quantity,
            # which is how the source cart behaves.
            conn.execute(
                "INSERT INTO clone_cart_line (cart_id, sku_id, product_slug, color, size, quantity, unit_price, list_price)"
                " VALUES (?,?,?,?,?,?,?,?)"
                " ON CONFLICT(cart_id, sku_id) DO UPDATE SET quantity = quantity + excluded.quantity",
                (cart_id, sku_id, product_slug, color, size, quantity, unit_price, list_price))
            conn.commit()
        finally:
            conn.close()


def set_line_quantity(actor: str, sku_id: str, quantity: int) -> None:
    with _lock:
        conn = _connect()
        try:
            cart_id = _cart_id(conn, actor)
            if quantity <= 0:
                conn.execute("DELETE FROM clone_cart_line WHERE cart_id = ? AND sku_id = ?", (cart_id, sku_id))
            else:
                conn.execute("UPDATE clone_cart_line SET quantity = ? WHERE cart_id = ? AND sku_id = ?",
                             (quantity, cart_id, sku_id))
            conn.commit()
        finally:
            conn.close()


def remove_line(actor: str, sku_id: str) -> None:
    set_line_quantity(actor, sku_id, 0)


def clear_cart(actor: str) -> None:
    with _lock:
        conn = _connect()
        try:
            conn.execute("DELETE FROM clone_cart_line WHERE cart_id IN (SELECT id FROM clone_cart WHERE actor = ?)",
                         (actor,))
            conn.commit()
        finally:
            conn.close()


def merge_cart(source_actor: str, target_actor: str) -> None:
    """Carry an anonymous cart into the member cart on sign-in."""
    if source_actor == target_actor:
        return
    with _lock:
        conn = _connect()
        try:
            src = conn.execute("SELECT id FROM clone_cart WHERE actor = ?", (source_actor,)).fetchone()
            if not src:
                return
            target_id = _cart_id(conn, target_actor)
            for row in conn.execute("SELECT * FROM clone_cart_line WHERE cart_id = ?", (src["id"],)).fetchall():
                conn.execute(
                    "INSERT INTO clone_cart_line (cart_id, sku_id, product_slug, color, size, quantity, unit_price, list_price)"
                    " VALUES (?,?,?,?,?,?,?,?)"
                    " ON CONFLICT(cart_id, sku_id) DO UPDATE SET quantity = quantity + excluded.quantity",
                    (target_id, row["sku_id"], row["product_slug"], row["color"], row["size"],
                     row["quantity"], row["unit_price"], row["list_price"]))
            conn.execute("DELETE FROM clone_cart WHERE id = ?", (src["id"],))
            conn.commit()
        finally:
            conn.close()


def cart_totals(lines: list[dict[str, Any]]) -> dict[str, float]:
    subtotal = round(sum(x["unit_price"] * x["quantity"] for x in lines), 2)
    savings = round(sum((x["list_price"] - x["unit_price"]) * x["quantity"] for x in lines), 2)
    shipping = 0.0 if (subtotal >= FREE_SHIPPING_THRESHOLD or not lines) else STANDARD_SHIPPING
    tax = round(subtotal * TAX_RATE, 2)
    return {"subtotal": subtotal, "savings": savings, "shipping": shipping,
            "tax": tax, "total": round(subtotal + shipping + tax, 2)}


# --------------------------------------------------------------------------
# wish list
# --------------------------------------------------------------------------

def wishlist(actor: str) -> list[dict[str, Any]]:
    conn = _connect()
    try:
        rows = conn.execute("SELECT * FROM clone_wishlist WHERE actor = ? ORDER BY added_at DESC, id DESC",
                            (actor,)).fetchall()
        return [dict(r) for r in rows]
    finally:
        conn.close()


def toggle_wishlist(actor: str, product_slug: str, color: str | None) -> bool:
    with _lock:
        conn = _connect()
        try:
            row = conn.execute(
                "SELECT id FROM clone_wishlist WHERE actor = ? AND product_slug = ? AND IFNULL(color,'') = IFNULL(?,'')",
                (actor, product_slug, color)).fetchone()
            if row:
                conn.execute("DELETE FROM clone_wishlist WHERE id = ?", (row["id"],))
                conn.commit()
                return False
            conn.execute("INSERT INTO clone_wishlist (actor, product_slug, color) VALUES (?,?,?)",
                         (actor, product_slug, color))
            conn.commit()
            return True
        finally:
            conn.close()


# --------------------------------------------------------------------------
# orders and addresses
# --------------------------------------------------------------------------

def orders(actor: str) -> list[dict[str, Any]]:
    conn = _connect()
    try:
        rows = conn.execute("SELECT * FROM clone_order WHERE actor = ? ORDER BY placed_on DESC", (actor,)).fetchall()
        out = []
        for r in rows:
            rec = dict(r)
            rec["lines"] = json.loads(rec["lines"])
            out.append(rec)
        return out
    finally:
        conn.close()


def order(actor: str, order_number: str) -> dict[str, Any] | None:
    for o in orders(actor):
        if o["order_number"] == order_number:
            return o
    return None


def addresses(actor: str) -> list[dict[str, Any]]:
    conn = _connect()
    try:
        rows = conn.execute("SELECT * FROM clone_address WHERE actor = ? ORDER BY is_default DESC, id", (actor,)).fetchall()
        return [dict(r) for r in rows]
    finally:
        conn.close()


def record_outbox(channel: str, recipient: str, purpose: str) -> None:
    """Marketing sign-ups land in a local outbox; nothing leaves the machine."""
    with _lock:
        conn = _connect()
        try:
            conn.execute("INSERT INTO clone_outbox (channel, recipient, purpose) VALUES (?,?,?)",
                         (channel, recipient, purpose))
            conn.commit()
        finally:
            conn.close()


def outbox() -> list[dict[str, Any]]:
    conn = _connect()
    try:
        return [dict(r) for r in conn.execute("SELECT * FROM clone_outbox ORDER BY id DESC").fetchall()]
    finally:
        conn.close()


SEED_ACCOUNTS = [{
    "subject_id": "backcountry-member-demo",
    "email": MEMBER["email"],
    "display_name": f'{MEMBER["first_name"]} {MEMBER["last_name"]}',
    "password": MEMBER["password"],
}]

SITE_TABLES = ("clone_cart_line", "clone_cart", "clone_wishlist",
               "clone_order", "clone_address", "clone_outbox")


def _site_reset(connection: sqlite3.Connection) -> None:
    for table in SITE_TABLES:
        connection.execute(f"DELETE FROM {table}")
    # DELETE leaves the AUTOINCREMENT high-water mark behind, so row ids would
    # creep on every reset and two resets would not produce identical state.
    connection.execute(
        "DELETE FROM sqlite_sequence WHERE name IN ({})".format(
            ",".join("?" for _ in SITE_TABLES)),
        SITE_TABLES)


def reset_state() -> None:
    """Deterministic reset: auth rows, mail flows and this site's business
    tables are cleared and reseeded in one transaction through the shared
    auth store, so a reset also clears mail rate limits and restores the
    seeded member's password."""
    with _lock:
        services().auth.reset_site_state(site_reset=_site_reset, seed_accounts=SEED_ACCOUNTS)
    seed_member_data()